1

在这里,我有五个要提取的表的数据。

表 1users包含三列:

uid, username, data

表 2users_order包含三列:

uid, orders_id, users_email

表 3order_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 数据的查询的帮助。

4

1 回答 1

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;

SQL 小提琴演示

这会给你:

| UID |   USERNAME | ORDERID |     USEREMAIL | PRODUCTNAME | FIRST NAME | LAST NAME |
-------------------------------------------------------------------------------------
|   1 | xxusername |     123 | xxxuser@gmail |   product 1 |        sam |       lin |

假设values用户配置文件表中的每个条目都有两个fid值 1、2 表示firstnamelastname

于 2012-12-18T01:37:04.410 回答