MYSQL基于另一个表条目选择查询

时间:2016-07-26 15:18:12

标签: mysql sql mysqli

我有一个类似于以下

的SQL查询
SELECT   * 
FROM     invoices_product 
WHERE    FROM_UNIXTIME(unixstamp, '%y%m%d') >= '160701' 
AND      FROM_UNIXTIME(unixstamp, '%y%m%d') <= '160730'

我现在面临的问题是,我只希望根据位于另一个名为user_id的表中的invoices获取特定用户的行,我还想选择{来自zname的{​​1}}。

invoices

2 个答案:

答案 0 :(得分:2)

在两个表之间使用INNER JOIN

SELECT ip.*, i.zname
FROM invoices_product ip
INNER JOIN invoices i
    ON ip.invoice_id = i.id
WHERE FROM_UNIXTIME(unixstamp, '%y%m%d') >= '160701' AND
      FROM_UNIXTIME(unixstamp, '%y%m%d') <= '160730' AND
      i.user_id = 'some_value'   -- this condition restricts to a given user

答案 1 :(得分:1)

您可以在两个表格上执行JOIN,例如

SELECT ip.* ,i.zname
FROM invoices_product ip 
JOIN invoices i ON ip.invoice_id = i.id
WHERE FROM_UNIXTIME(ip.unixstamp, '%y%m%d') >= '160701' 
AND FROM_UNIXTIME(ip.unixstamp, '%y%m%d') <= '160730'
AND i.user_id = 1234;