我有两张表,结构如下:
Custom Pricing List
+------------+--------------+------------ +
| stock_code | stored_price | pricing_ref |
+------------+--------------+------------ +
Generic Pricing List
+------------+---------------------+--------------+-------------+--------------+
| stock_code | last_purchase_price | sales_price | description | qty_in_stock |
+------------+---------------------+--------------+-------------+--------------+
我想返回的是:
+------------+---------------------+--------------+--------------+-------------+
| stock_code | last_purchase_price | sales_price | description | qty_in_stock |
+------------+---------------------+--------------+--------------+-------------+
目前我只查询最后一个表,使用以下MySQL语句:
SELECT * FROM $table WHERE $column LIKE '%$term%' $or LIMIT 0,10
不过,我希望合并2,并且仍然能够对
stock_code
列进行通配符搜索。所有结果都必须返回
description
和qty_in_stock
。结果中的sales_price
要么是stored_price
中的Custom Pricing Table
要么是sales_price
中的Generic Pricing Table
但是stored_price
优先于sales_price
中的Generic Pricing Table
。我知道我需要做一个联合查询,但我不确定如何才能写它。
编辑
使用语句:
SELECT stock.*, price.*
FROM stock
LEFT INNER JOIN price
ON stock.stock_code = price.stock_code
WHERE stock.stock_code LIKE '%123%'
LIMIT 0,10
我现在收到以下错误:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN price
ON stock.stock_code = price.stock_code
WHERE stock.stoc' at line 3
最佳答案
我想你可以把两张桌子都合上。试试这个:
SELECT
generic.stock_code,
generic.last_purchase_price,
IFNULL(custom.stored_price, generic.sales_price) AS actual_price,
generic.description,
generic.qty_in_stock
FROM
Generic_Pricing_List generic
JOIN Custom_Pricing_List custom
on custom.stock_code = generic.stock_code
WHERE $column LIKE '%$term%' $or LIMIT 0,10;
如果存储的价格不为空且已定义,则将提取该价格。否则,将收取销售价格。
关于php - 合并2个MySQL表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32011369/