Fetch data from 4 tables mysql - php

I have 4 tables as below
Table1: restos
Structure:
resu_id resu_name resu_address
-------------------------------------
1 ABC Exapmple
2 DEF Example
3 GHD Example
Table2:foodtype
Structure:
id typename
---------------
12 Indian
23 Punjabi
Table3: resto_foodtypes
Structure:
resu_id foodty_id
--------------------
1 12
2 23
3 12
Table4: discnts
Structure:
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.
below is the query that m using
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. For e.g. resu_id=3 is not present in discnts table.

To exclude results that have no entry in discnts table, use a INNER JOIN instead of a LEFT JOIN.
To include these results, but have a 0 displayed (instead of the defaults NULL), you can use IFNULL(expr, 0) function:
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.

Related

MySQL: Select several rows based on several keys from two different tables

I have these two tables - user_schedules and user_schedule_meta, shown below:
------------------------------------
| id | scheduler_id | status |
------------------------------------
1 3 pending
2 5 active
3 6 active
and
----------------------------------------------
| id | user_schedule_id | meta_key |meta_value
----------------------------------------------
1 3 course-id 135
2 3 session-id 15
3 3 schedule-id 120
I want to write a query to enable me select, for example, from both tables where EVERYONE of the below 5 conditions are met:
user_schedule_id = 3
scheduler_id = 6
session_id = 15
course-id = 135
schedule-id = 120
This is what I have so far, but it is not working:
SELECT user_schedule_meta.`id` FROM user_schedule_meta, user_schedules
WHERE user_schedules.`scheduler_id` = 6
AND user_schedules.id = user_schedule_meta.`user_schedule_id`
AND (
(user_schedule_meta.`meta_key` = 'course-id' AND user_schedule_meta.`meta_value` = 135)
OR (user_schedule_meta.`meta_key` = 'session-id' AND user_schedule_meta.`meta_value` = 15)
OR (user_schedule_meta.`meta_key` = 'daily-schedule-id' AND user_schedule_meta.`meta_value` = 120)
)
GROUP BY user_schedule_meta.`id`
Any suggestions what I am not doing right?
This is a typical key-value store lookup problem. These are trickier than they look in SQL, in that they require multiple JOIN operations.
You need a virtual table with one row per user_schedules.id value, then you can filter it. So
SELECT u.id, u.scheduler_id
FROM user_schedules u
JOIN user_schedule_meta a ON u.id=a.user_schedule_id AND a.meta_key='course-id'
JOIN user_schedule_meta b ON u.id=b.user_schedule_id AND b.meta_key='session-id'
JOIN user_schedule_meta c ON u.id=c.user_schedule_id AND c.meta_key='daily-schedule-id'
WHERE a.meta_value = 135 -- value associated with course-id
AND b.meta_value=15 -- value associated with session-id
AND c.meta_value=120 -- value associated with daily-schedule-id
Notice also that you can list your table with associated attributes like this. This trick of joining the key/value table multiple times is a kind of pivot operation. I use LEFT JOIN because it will allow the result set to show rows where an attribute is missing.
SELECT u.id, u.scheduler_id, u.status,
a.meta_value AS course_id,
b.meta_value AS session_id,
c.meta_value AS daily_schedule_id
FROM user_schedules u
LEFT JOIN user_schedule_meta a ON u.id=a.user_schedule_id AND a.meta_key='course-id'
LEFT JOIN user_schedule_meta b ON u.id=b.user_schedule_id AND b.meta_key='session-id'
LEFT JOIN user_schedule_meta c ON u.id=c.user_schedule_id AND c.meta_key='daily-schedule-id'
try this is code
select * from user_schedule_meta where user_schedule_id=3 and
(meta_key='session-id' AND meta_value=15
or meta_key='daily-schedule-id' AND meta_value=120
or meta_key='course-id' AND meta_value=135
)

Mysql select multiple count giving wrong values

I'm trying to find a patient's appointments and messages count. My table records are like below 3 table patient, appointments and messages
Patient table
pid fname lname
1 john sid
2 rother ford
3 megan rough
4 louis kane
appointments table
id pid appointment_date
1 1 2015-08-04
2 2 2015-08-05
3 1 2015-08-06
4 1 2015-08-07
5 3 2015-08-07
6 2 2015-08-08
7 4 2015-08-13
8 1 2015-08-12
Messages table
id pid description message_date
1 2 join 2015-08-04
2 2 update 2015-08-05
3 3 join 2015-08-05
4 4 update 2015-08-10
5 3 test 2015-08-07
So if write query to find counts i'm getting wrong values
SELECT pd.fname,pd.lname , pd.pid, COUNT( a.id ) AS app_cnt, COUNT( m.id ) AS mes_cnt
FROM patient pd
LEFT OUTER JOIN appointments a ON a.pid = pd.pid
LEFT OUTER JOIN messages m ON m.pid = pd.pid
GROUP BY pd.pid
ORDER BY pd.pid
fname lname pid app_cnt mes_cnt
john sid 1 4 0
rother ford 2 4 4
megan rough 3 2 2
louis kane 4 1 1
Here pid 1 have 4 appointments and 0 messages, pid 2 have 2 appointments and 2 messages but getting wrong values.
Can someone please help to resolve this issue. I'm not interested in writing sub queries for this.
Functionality looks simple but I'm really facing problem for writing query.
Anymore suggestions please.
After thoroughly analysing your problem and tables, It cannot be done directly using simple query as LEFT OUTER JOIN is returning some superfluous records, that's why to filter it, you will have to use temporary table and modify the query as:
Select temp.fname, temp.lname, temp.pid, a_count, count(m.pid) as m_count from
(SELECT fname,lname,pd.pid, count(a.pid) as a_count
FROM patients pd
LEFT OUTER JOIN appointments a ON a.pid = pd.pid group by pd.pid) temp
LEFT OUTER JOIN messages m ON m.pid = temp.pid
group by temp.pid
Explanation:
It will join patients and appointments table and group them by pid so that messages from message table do not repeat for each patients.pid.
The wrong result is as a result of left outer join as it is giving wrong results for this query
SELECT *
FROM patients pd
LEFT OUTER JOIN appointments a ON a.pid = pd.pid
LEFT OUTER JOIN messages m ON m.pid = pd.pid
Since we need to limit the results of first two joins, hence temporary table is necessary.

Exclude result from MySQL query in JOIN

I have multiple tables with orders and deliveries and I want to get only open orders (only those orders that do not have records in delivery table).
So, my tables look like:
Orders table (sh_comenzi):
id partner
1 Partner X
2 Partner Y
3 Partner Z
4 Partner Q
Order lines table (sh_comenzi_pos) where idc is the id of sh_comenzi table
id idc cPos quantity
1 1 1 5
2 1 2 10
3 1 3 20
4 2 1 10
5 2 2 15
6 3 1 10
7 3 2 5
8 3 3 8
9 4 1 15
The deliveries items table is (sh_delivery_items)
id idc cPos
1 1 1
2 1 3
3 2 2
4 3 1
5 3 2
6 3 3
The desired result should give me an output of open orders just like this:
id partner
1 Partner X
2 Partner Y
4 Partner Q
The result doesn't have to keep track o quantities, just on lines level. If one line from orders exists in sh_delivery_items then that line is closed.
I tried something like this:
SELECT DISTINCT sh_comenzi.id, partner FROM sh_comenzi
LEFT JOIN sh_comenzi_pos ON sh_comenzi.id = sh_comenzi_pos.idc
LEFT JOIN sh_delivery_items ON (sh_comenzi_pos.idc = sh_delivery_items.idc AND sh_comenzi_pos.cPos = sh_delivery_items.cPos)
WHERE sh_comenzi.id IS NOT NULL
ORDER BY sh_comenzi.id DESC
Could someone help me?
This is the query you need:
SELECT DISTINCT c.*
FROM sh_comenzi c
INNER JOIN sh_comenzi_pos p
ON c.id = p.idc
LEFT JOIN sh_delivery_items di # 'di' from 'delivery items'
ON p.idc = di.idc AND p.cPos = di.cPos
WHERE di.id IS NULL # keep only not-delivered items
How it works
It combines all the orders (table sh_comenzi) with their line items (table sh_comenzi_pos). The INNER JOIN will leave out the empty orders (if any); if you need them then use LEFT JOIN instead.
Next, each row (order, line item) is combined with the delivery information (table sh_delivery_items) using the pair of columns (idc, cPos). The LEFT JOIN ensures all the rows from the left side table (or result set) appear in the final result set; if a row from the right side table cannot be found to match the row from the left, a row full of NULLs is used instead. This happens for the line items that were not delivered yet (there is no record for them in sh_delivery_items).
Then, the WHERE clause keeps only the rows having NULLs in the di table (sh_delivery_items), i.e. the line items that were not delivered, together with the orders that own them.
Finally, SELECT DISTINCT c.* selects only the columns from the orders table (sh_comenzi) and DISTINCT ensures each order appear only once. Otherwise, each order appears once for each of its line items that was not delivered.
Complete the query yourself with the desired ORDER BY clause.

Return all the rows even the joined table has empty results

In my table 1 I have something like this
name | age
George 42
Bob 30
Ken 23
In my table 2, I have something like this, this is where i store votes for each person.
name | votes |
George 1
Ken 1
George 1
George 1
Ken 1
My goal is to combine the 2 tables, and return all the rows in table 1 even it doesn't exist in table 2.
Desire results:
name | age | total_votes
George 42 3
Bob 30 0
Ken 23 2
But instead I get:
name | age | total_votes
George 42 3
Ken 23 2
I have tried something like this
SELECT `table_1`.*, coalesce(COUNT(`table_2`.votes), 0) AS total_votes
FROM `table_1`
LEFT JOIN `table_2`
ON `table_1`.name = `table_2`.name
You can do one of these:
1) Use Right Join instead of current Left Join.
Or
2) Exchange table1 and table2 places in your join expression, like:
FROM table_2
LEFT JOIN table_1
Try this. This works in MS Access , I think this will work on your's too just convert the query to SQL:
SELECT Table1.name, First(Table1.age) AS age, Count(Table2.Votes) AS totalVotes
FROM Table1 LEFT JOIN Table2 ON Table1.name = Table2.name
GROUP BY Table1.name;
Left Join table1 to table2 so that all entry from table1 , even if its is corresponding data is null, will be included. GROUP BY your query by name so that votes will be counted by name .

MySql Select Result Having Combined Multiple Queries From Both the Same Table and Others

I have a table ('names') which includes data related with other data in other tables relying on ids. For example:
*Names table
id | name | predecessor | successor | house | birthplace
-----------------------------------------------------------------
10 Bayezid II 9 11 4 NULL
11 Selim I 10 12 4 5
12 Suleiman 11 13 4 61
*Houses table
id | house
--------------
4 House of Osman
*Places table
id | place
--------------
5 Amasya
61 Trabzon
What I'm trying to accomplish is to construct a query which results in returning whole information depending on the id, like:
{"result":[{
"id":"11",
"name":"Selim I",
"predecessor": "Bayezid II",
"successor": "Suleiman",
"house":"House of Osman",
"birthplace":"Amasya"
}]}
So, the name of the house and the birthplace are brought from other tables ('houses', 'places') whereas the predecessor and the successor are from the same table. I need help constructing this query. Thank you.
Just self-join a couple times, once to get the predecessor's row (aliased n0 below), and once more for the successor's (n2):
SELECT n1.id, n1.name, n0.name AS predecessor, n2.name AS successor
FROM names n1
LEFT JOIN names n0 ON n1.predecessor = n0.id
LEFT JOIN names n2 ON n1.successor = n2.id
SQL Fiddle demo
Joining to get the house and birthplace are left as an exercise for the reader.
Try this:
select n.id,
n.name,
n1.name as predecessor,
n2.name as successor,
h.house,
p.place
from names n
inner join names n1 on n.id = n1.predecessor
inner join names n2 on n.id = n2.successor
left join Houses h on n.house = h.id
left join Place p on n.birthplace = p.id
where n.id = 11

Categories