简体   繁体   中英

How to join 2 tables that share 1 colum with same ID and add WHERE clause to it

Well, the title says it all.

I have tried several things none of them worked till now I have this:

SELECT *
FROM ".$CFG['table']['menuaddons']." m
JOIN ".$CFG['table']['addons']." t1 ON m.addonparentid = t1.id
JOIN ".$CFG['table']['addons']." t2 ON m.addonparentid = t2.id
";

This returns all the items. Now I only want to show the items where the m.addonparentid is a variable $parentid .

When I do:

SELECT *
FROM ".$CFG['table']['menuaddons']." m
JOIN ".$CFG['table']['addons']." t1 ON m.addonparentid = t1.id
JOIN ".$CFG['table']['addons']." t2 ON m.addonparentid = t2.id
WHERE m.addonparentid = '".$menuaddonsid."'
";

I get an empty array back? And when that works I want to sort it DESC on a column name called addonsort in .$CFG['table']['addons']. .

I have checked all info about join but could not find how to do this.

It's a little tricky to work this out without knowing a) your intention and b) the schema of the tables involved. Why do you need the add-ons table in the query twice?

Maybe this will work?

$query = "SELECT *
FROM " . $CFG['table']['menuaddons'] . " m
INNER JOIN " . $CFG['table']['addons'] . " t1 ON m.addonparentid = t1.id
WHERE m.addonparentid = " . $parentid . "
ORDER BY t1.addonsort DESC";

If not, please post more information. Once you have it working, please consider converting this to using PDO - the current query is vulnerable to SQL injection, depending on where the variables come from.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM