简体   繁体   中英

Joining multiple tables but not all

I'm wanting to join the results based on Table1 ( product ) and Table3 ( system_type ) . Whereas Table2 ( system_cat ) doesn't include the column I want to join. How can I join Table1 and Table2, but only join Table1 and Table3 in one statement?

Current non-joined version:

 SELECT * FROM product LEFT JOIN system_cat USING (cat_id) LEFT JOIN system_type USING (type_id) WHERE system_furniture_check = 0 AND cat_id = :c ORDER BY sortorder

Joined non-working version (attempt 1):

 SELECT * FROM product LEFT JOIN system_cat USING (cat_id) LEFT JOIN system_type USING (type_id) WHERE system_furniture_check = 0 AND cat_id = :c ORDER BY sortorder 

Alternative joined non-working version (attempt 2):

SELECT product.*, system_cat.*, system_type.* 
FROM product 
JOIN system_cat 
ON system_cat.cat_id = product.cat_id 
JOIN system_type 
ON system_type.type_id = product.type_id 
WHERE system_furniture_check = 0 AND cat_id = :c ORDER BY sortorder

The error:

Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'cat_id' in where clause is ambiguous

Tables:

  • product – type_id, cat_id
  • system_cat – cat_id
  • system_type – type_id, cat_id

As it says you need to prefix table qualifier. Try this. Also do not use *, just type out the required columns

SELECT product.*, system_cat.*, system_type.* 
FROM product 
JOIN system_cat 
ON system_cat.cat_id = product.cat_id 
JOIN system_type 
ON system_type.type_id = product.type_id 
WHERE system_furniture_check = 0 AND system_cat.cat_id = :c ORDER BY sortorder

You need to add a table name (or alias) before cat_id in your where clause.
Use the modified query below, replacing ???? with the tablename that you want to use.

SELECT product.*, system_cat.*, system_type.* 
FROM product 
JOIN system_cat USING (cat_id)
JOIN system_type USING (type_id)
WHERE system_furniture_check = 0 
AND ????.cat_id = :c 
ORDER BY sortorder

Its also OK to use 'USING' if the columns you are matching on are the same name.

Try this, you are missing the qualifier for the tables:

SELECT p, sc, st 
FROM product p
INNER JOIN system_cat sc
ON sc.cat_id = p.cat_id
INNER JOIN system_type st
ON st.type_id = p.type_id 
WHERE system_furniture_check = 0 AND sc.cat_id = :c ORDER BY sortorder;

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