2016-05-13 16 views
6

Ho una lista di elementi (Brand + productModel) in una tabella mysql, e ho una lista di Marchi in un'altra tabella.mysql/php: trova stringa iniziale nella stringa

esempio:

table_items

|id| name    | brand_id | 
----------------------------------- 
| 1| Apple Mac 15  |   
| 2| Dell Laptop NXY | 
| 3| HP Tablet 15  | 
| 4| Apple Laptop AA | 
| 5| Dell Tablet VV | 
| 6| HP Desktop XYZ | 

table_brands

|id| name | 
------------ 
| 1| Apple | 
| 2| Dell | 
| 3| HP | 

ho ereditato il table_items da un precedente progetto quindi ho bisogno di rilevare il marchio in table_items, se il marchio è presente, quindi aggiungere il marchio id al brand_id colonna di voce (vuoto)

così l'uscita ideale sarebbe

|id| name    | brand_id | 
----------------------------------- 
| 1| Apple Mac 15  | 1 
| 2| Dell Laptop NXY | 2 
| 3| Dell Tablet 15 | 2 
| 4| Apple Laptop AA | 1 
| 5| HP Tablet VV  | 3 
| 6| HP Desktop XYZ | 3 

quindi non so se devo usare PHP o può essere fatto in MySQL direttamente .. e se PHP come rilevare le stringhe corrispondenti?

+1

Sì, può essere fatto direttamente in mysql. – DD77

risposta

1

è possibile utilizzare la query in MySQL come

SELECT id FROM TABLE_BRANDS WHERE name like "Dell%"; 
1

trovo quello che si vuole fare è simile per la ricerca ed è meglio con MySQL.

Segue la query per ottenere tutti gli articoli simili con il jolly.

SELECT * FROM brand_table WHERE name LIKE "Apple%" 

Appariranno tutti i nomi che iniziano con le mele. Spero che tu prenda la deriva qui

1

È molto meglio che tu gestisca all'interno del Database se riesci a trovare una query corretta.

si può provare la seguente query:

SELECT ti.id, ti.name, tb.id as brand_id 
FROM table_items ti LEFT JOIN table_brands tb ON ti.name LIKE CONCAT(tb.name, '%'); 
7

Puoi partecipare sia tabella utilizzando come e aggiornamento, se necessario.

UPDATE `table_items` TI 
INNER JOIN table_brands TB 
    ON TI.name LIKE CONCAT(TB.name, '%') 
SET TI.brand_id = TB.id 

Nota: INNER JOIN aggiornerà soltanto i campi che sono abbinati.

1

Questa query farà il lavoro.

UPDATE table_items 
     JOIN table_brands 
     ON table_items.name LIKE CONCAT('%', table_brands.name ,'%') 
SET table_items.brand_id = table_brands.id; 
1

Ecco la query più semplice, senza per tuffarsi unisce:

UPDATE table_items SET brand_id = (SELECT id FROM table_brands WHERE `Name` = SUBSTRING_INDEX(table_items.name,' ',1)) 
0

Il modo più semplice per farlo è usare direttamente SQL.

La query più semplice che fare il lavoro è:

UPDATE table_items 
    SET brand_id = (SELECT id FROM table_brands 
        WHERE table_items.name LIKE CONCAT(name,'%'))