Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Join using "contains"?

Tags:

join

mysql

I have these two tables:

Table: ORDERS
ID - NAME    - DATA
---------------------------------------------
1  - Order 1 - node_checkout_nid";i:141;s:10:
2  - Order 2 - node_checkout_nid";i:142;s:10:

Table: NODES
NID - Description
--------------------
141 - bla bla bla
142 - bla bla bla 2

I need a SQL join query that can join the two tables on NID, keeping in mind the NID is in the "DATA" column.

I need to end with this:

Table: RESULT
ID - NAME    - DATA                             NID - Description
-----------------------------------------------------------------------------------
1  - Order 1 - node_checkout_nid";i:141;s:10: - 141 - bla bla bla
2  - Order 2 - node_checkout_nid";i:142;s:10: - 142 - bla bla bla 2

I wanted to use a "like" join, but I think (if it's possible) a "contains" join would be better? Any help would be greatly appreciated!

like image 293
coderama Avatar asked Feb 09 '11 08:02

coderama


People also ask

Can we use join in with clause?

You can use the USING clause for a shorthand way of defining join conditions. The USING clause is equivalent to a join condition where each column from the left table is compared to a column with the same name in the right table.

How Write outer join in MySQL?

The syntax for the RIGHT OUTER JOIN in MySQL is: SELECT columns FROM table1 RIGHT [OUTER] JOIN table2 ON table1. column = table2.

Can we use join without on condition?

We can use 'cross join' without on condition. Cross join gives the result in cartesian product form. For instance, if in one table there are 3 records and another table has 2 records, then the first record will match with all the second table records. Then, the same process will be repeated for second record and so on.


2 Answers

You can use:

SELECT ID, NAME, DATA, NID, Description
  FROM ORDERS INNER JOIN NODES ON DATA LIKE CONCAT('%;i:', NID, ';%')

Anyway it's a heavy query. It's not a good idea to have the NID inside the data field as a plain text, better in a different column.

like image 117
Borja Avatar answered Oct 17 '22 03:10

Borja


You data is denormalised. You're storing some serialized object in DATA column and are trying to perform relational operations basing on that. While it is possible to do so, mind that it will be slow and potentially unreliable. Just store your NID in a separate column.

like image 33
Mchl Avatar answered Oct 17 '22 04:10

Mchl