[英]Fetch data from 4 tables mysql
I have 4 tables as below 我有4张桌子如下
Table1: restos
Structure: 表1: restos
结构:
resu_id resu_name resu_address
-------------------------------------
1 ABC Exapmple
2 DEF Example
3 GHD Example
Table2: foodtype
Structure: 表2: foodtype
结构:
id typename
---------------
12 Indian
23 Punjabi
Table3: resto_foodtypes
Structure: 表3: resto_foodtypes
结构:
resu_id foodty_id
--------------------
1 12
2 23
3 12
Table4: discnts
Structure: 表4: discnts
结构:
id resu_id amt_dscPer(%age discount)
---------------------------
19 1 15
20 2 25
Now i want to display the restaurant along with discounts available for the restauarant. 现在,我想显示餐厅以及可供餐厅使用的折扣。 Currently restaurants are getting displayed but for the restaurant not present in discnts
table are returning null values from discnts
table. 当前正在显示餐厅,但对于不存在于discnts
表中的餐厅, discnts
正在从discnts
表返回空值。
below is the query that m using 以下是m使用的查询
SELECT * from `restos` r join resto_foodtypes rf on rf.resu_id = r.resu_id
join foodtype f on rf.foodty_id = f.id left join discnts dcfm on
r.resu_id= dcfm.resu_id where true;
I want that the restaurants that are not present in discnts
table should not be included in resultset. 我希望结果表中不包含在discnts
表中不存在的餐厅。 For eg resu_id=3
is not present in discnts
table. 例如, discnts
表中不存在resu_id=3
。
To exclude results that have no entry in discnts table, use a INNER JOIN
instead of a LEFT JOIN
. 要排除在discnts表中没有条目的结果,请使用INNER JOIN
而不是LEFT JOIN
。
To include these results, but have a 0
displayed (instead of the defaults NULL
), you can use IFNULL(expr, 0)
function: 要包括这些结果,但显示为0
(而不是默认值NULL
),可以使用IFNULL(expr, 0)
函数:
SELECT
r.resu_name AS Name,
f.typename AS Food,
IFNULL(dcfm.amt_dscPer, 0) AS Discount
FROM `restos` r
JOIN resto_foodtypes rf ON rf.resu_id = r.resu_id
JOIN foodtype f ON rf.foodty_id = f.id
LEFT JOIN discnts dcfm ON r.resu_id= dcfm.resu_id;
IFNULL returns the first parameter if it is not null, the second if expr
is indeed null. IFNULL如果不为空,则返回第一个参数,如果expr
实际上为空,则返回第二个参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.