这里我有五张桌子的数据。
表1 users
有三列:
uid, username, data
表2 users_order
有三列:
uid, orders_id, users_email
表3 order_products
有三列:
orders_id, product_id, product_name
表4用户配置文件值有三列(下面是行中的数据)
uid, fid, values
1 1 firstname
1 2 lastname
因此,通过表1 - 3,我能够像这样编写查询
SELECT users.uid AS uid, users.username AS username,
users_order.orders_id AS orderId,
users_order.users_email AS userEmail,
order_products.product_name AS productName
WHERE users_order.uid = users.uid
AND users_order.orders_id = order_products.orders_id
AND order_products.product_id = 5 ;
以上查询将给出
的结果uid usersname orderId usersEmail productName
1 xxusername 123 xxxuser@gmail Product 1
我想将表4数据Firstname和Last Name引入查询结果。 所以,最终的查询将是
uid username orderId usersEmail productName FirstName LastName
需要有关添加表4数据的查询的帮助。
答案 0 :(得分:1)
试试这个:
SELECT
u.uid AS uid,
u.username AS username,
o.orders_id AS orderId,
o.users_email AS userEmail,
p.product_name AS productName,
MAX(CASE WHEN f.fid = 1 THEN `values` END) AS 'First Name',
MAX(CASE WHEN f.fid = 2 THEN `values` END) AS 'Last Name'
FROM users u
INNER JOIN users_order o ON o.uid = u.uid
INNER JOIN order_products p ON o.orders_id = o.orders_id
INNER JOIN usersprofile f ON u.uid = f.uid
WHERE p.product_id = 5
GROUP BY u.uid, u.username, o.orders_id, o.users_email, p.product_name;
这会给你:
| UID | USERNAME | ORDERID | USEREMAIL | PRODUCTNAME | FIRST NAME | LAST NAME |
-------------------------------------------------------------------------------------
| 1 | xxusername | 123 | xxxuser@gmail | product 1 | sam | lin |
假设用户个人资料表中的每个values
条目都有两个fid
值1,2,表示firstname
和lastname
。