Compare row result and create new column - php

I will like to compare row results and create a new column when a specific column have the same fightID.
My query:
SELECT fight.fightdato, fight.fightID, players.name,
playersfight.playerid, playersfight.playerScore
FROM fight
INNER JOIN playersfight ON fight.fightID = playersfight.fightID
INNER JOIN players ON playersfight.playerID = players.playersID
Result in php:
Fight Fight Date Player PlayerScore
1 2014-10-10 Kevin 8
1 2014-10-10 Chris 4
2 2014-09-01 Kevin 8
2 2014-09-01 Eric 4
My wanted result:
Fight Fight Date Player1 Result1 Player2 Result2
1 2014-10-10 Kevin 8 Chris 4
2 2014-09-01 Kevin 8 Eric 4
btw - I am new to php/mysql and programming in general
Thanks for helping me!

You need to join player and playerfight tables once more.
Something like:
SELECT fight.fightID, fight.fightdato,
p1.name as 'Player_1', pf1.playerid as 'PlayerID_1', pf1.playerScore as 'Result_1',
p2.name as 'Player_2', pf2.playerid as 'PlayerID_2', pf2.playerScore as 'Result_2'
FROM fight
JOIN playersfight pf1 ON fight.fightID = pf1.fightID
JOIN players p1 ON pf1.playerID = p1.playersID
JOIN playersfight pf2 ON fight.fightID = pf2.fightID
JOIN players p2 ON pf2.playerID = p2.playersID
WHERE p1.playersID < p2.players2
The WHERE clause with p1.playersID < p2.players2 condition excludes two cases that we don't want to have returned:
results with joined the same player twice in one row.
duplicates - for example for players with IDs 1 and 2 there would be returned the same fight twice with player IDs (1,2) and (2,1). Now it will return only first permutation.

Related

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.

Remove Duplicate Row Except The Last One

I have this table on MySql:
Table1
ID CODE USER NUMBER ADJUSTMENT ADJUST_DATE
1 abc Frank 10245 1 2015/04/20
2 def Jonathan 25410 0 2015/04/21
3 ghi Karen 55214 3 2015/05/05
4 abc Frank 10245 2 2015/04/21
5 abc Frank 10245 4 2015/04/22
I would like to remove the duplicated data and leave the last entry by date:
ID CODE USER NUMBER ADJUSTMENT ADJUS_DATE
2 def Jonathan 25410 0 2015/04/21
3 ghi Karen 55214 3 2015/05/05
5 abc Frank 10245 4 2015/04/22
CODE, USER, NUMBER, ADJUSTMENT, ADJUS_DATE are 'Unique'
I need to create a temporary table with the result because I need all the records.
Generate a subset of the max date grouped by like values in columns and join back to the base set...
SELECT A.ID, A.Code, A.user, A.Number, A.Adjustment, A.Adjust_date
FROM table1 A
INNER JOIN (SELECT Code, User, Number, max(adjust_date) mDate
FROM table1 group by Code, User, Number) B
on A.code = B.code
and A.user = B.User
and A.Number = B.Number
and A.Adjust_date = B.mdate

How to check if specific datetime was not used using multiple tables?

There are 3 tables: buildings, rooms, reservations.
1 building = n rooms
1 room = n reservations
TABLE BUILDINGS - ID(int), name(varchar)
TABLE ROOMS - ID(int), building_id(int)
TABLE RESERVATIONS - ID(int), room_id(int), date_start(datetime), date_end(datetime)
Buildings table example
<pre>
ID name
1 Building A
2 Building B
3 Building C
</pre>
Rooms table example
<pre>
ID building_id
1 1
2 1
3 2
4 3
</pre>
Reservations table example
<pre>
ID room_id date_start date_end
1 1 2014-08-09 14:00:00 2014-08-09 14:30:00
2 1 2014-08-09 14:30:00 2014-08-09 15:30:00
3 3 2014-08-09 16:30:00 2014-08-09 17:30:00
4 2 2014-08-09 16:00:00 2014-08-09 17:00:00
5 3 2014-08-09 16:00:00 2014-08-09 16:30:00
</pre>
Question
How to filter all buildings which have atleast 1 room available at the specific date and time?
For example we want to filter all buildings which have atleast 1 available room at 2014-08-09 16:00:00 until 2014-08-09 17:00:00. In this case it will show that Building A AND Building C are available. Building A has 1 free room and Building B also has 1 free room, because there is no reservation on that room.
Can someone help me out on this one? I just can not figure it out with a single MySQL query to get all buildings. Thank you.
Use LEFT JOIN to connect the rooms table to the reservations table, with the time condition in the on clause. Then, look where there are no matches -- these are rooms that are available.
SELECT b.id, b.name, COUNT(*) as NumRoomsAvailable
FROM buildings b JOIN
rooms r
ON b.id = r.building_id LEFT JOIN
reservations rv
ON rv.room_id = r.id AND
'2014-08-09 16:00:00' BETWEEN rv.date_start AND rv.date_end
WHERE rv.room_id is null
GROUP BY b.id;
The final step is just aggregating by the building, rather than listing each available room out separately.
Try this query
SELECT b.name,r.id,rv.date_start,rv.date_end FROM buildings b
LEFT JOIN rooms r ON b.id = r.building_id
LEFT JOIN reservataions rv ON rv.room_id = r.id
WHERE '2014-08-09 16:00:00' BETWEEN rv.date_start AND rv.date_end

comparing different columns and rows on the same table

We are making a simple database for our school programme. we have a table like this:
ID A B
1 John Stacey
2 Stacey Mark
3 Candice Rick
4 Stacey Rick
5 Rick Stacey
If we input Stacey's name, we display the number of rows where:
for every row (say, x and y)
rowX-ColumnA = rowY-ColumnB AND rowY-ColumnA = rowX-ColumnB
in this case, it should output:
2 rows:
4 Stacey Rick
5 Rick Stacey
Thanks! We have more than 100 students so we won't be able to do this manually. Again, I appreciate any hint.
Try this query my friend:
select t1.* from table1 t1
inner join table1 t2 on t1.A = t2.B and t1.B = t2.A;
SQL Fiddle
This will do it
SELECT p1.*
FROM People p1
INNER JOIN
People p2 ON p1.A=p2.B AND p1.B=p2.A
WHERE p1.A='Stacey' OR p1.B='Stacey'
See this SQLfiddle (SQL Server 2008)
Based on your example. I think you're probably looking for something like this:
select stu1.* from students stu1,
students stu2
where stu1.last_name = stu2.first_name
union
select stu1.* from students stu1,
students stu2
where stu1.first_name = stu2.last_name;
http://sqlfiddle.com/#!4/e9bbf/2/0
Above answer was based on your example of John Stacy , Stacy Rick.

Advanced mysql queries, fetching from several tables and rows at once. Joins?

I'm currently working on a project where I have information stored in several tables that all connect to each other. I believe that the table and column format is logical and the best choice. The problem though, is that I don't have enough knowledge to build queries advanced enough to fetch all the information I need.
The main table is ab_ads, where advertisements are stored. These ads can be assigned several formats (ie. 250x360, 980x120 etc), and you can also select the region where they should be showing (ie. Skåne, Stockholm, Kalmar, Dalarna, Jämtland etc).
This is how I store my data. I'm not showing all tables but I hope this is sufficient.
Advertisements column (ab_ads): (There are more columns but they are not relevant)
ID orgnum company_name title content link
1 556664-7524 Company Inc Lorem ipsum Lorem ipsum URL
Advertisement states (ab_ads_states):
ID adID stateID
1 1 2 // Skåne
2 1 5 // Kalmar
3 1 8 // Stockholm
4 1 10 // Värmland
5 2 2 // Skåne
6 2 5 // Kalmar
7 3 8 // Stockholm
8 4 10 // Värmland
Advertisement formats (ab_ads_formats)
ID adID formatID
1 1 1 // 250x360
2 1 2 // 980x120
3 2 1 // 250x360
4 3 2 // 980x120
Formats table (ab_formats)
ID name width height
1 Format 1 250 360
2 Format 2 980 120
So, I have two flash banners both are supposed to call a PHP-script which in turn is supposed to deliver an XML-file back with all the results.
I know how to select data from different tables, but I've never worked with selecting multiple rows from another table and merging them into one, which I suppose is that I need to do here. I'm very thankful for any help I can get.
The flash banners will send two parameters to the PHP file, stateID and formatID. Which means I have to SELECT ad WHERE state = param AND format = format. But since I store multiple entries for the ad states I don't know how to do it.
EDIT:
I would also like to fetch the format names in the query and get them in the following format: "Format 1,Format 2" in a column named "formats". I guess this would require some kind of join?
Thanks in advance!
I think this will work:
select ab.name as formats, aa.* from ab_ads as aa
inner join ab_ads_states as aas on aa.id = aas.adid and aas.stateId = stateIdParam
inner join ab_ads_formats as aaf on aa.id = aaf.adid and aaf.formatId = formatIdParam
inner join ab_formats as ab on aaf.formatid = ab.id
Edit:
I'm not very good with mySql, and don't have anything to test this on, but I think group_concat may be what you are looking for. If so, it will probably look something like this:
select group_concat(ab.name separator ", ") as formats from ab_ads aa
inner join ab_ads_states as aas on aa.id = aas.adid and aas.stateId = 2
inner join ab_ads_formats as aaf on aa.id = aaf.adid and aaf.formatId in(1,2)
inner join ab_formats as ab on aaf.formatid = ab.id
group by ab.id
Please try below SQL:
SELECT count(aaf.ID) AS TotalFormat,
group_concat(ab.name) AS formats
FROM ab_ads aa
INNER JOIN ab_ads_states AS aas ON aa.ID = aas.adID
AND aas.stateID = 2
INNER JOIN ab_ads_formats AS aaf ON aa.id = aaf.adID
AND aaf.formatID in(1,2)
INNER JOIN ab_formats AS ab ON aaf.formatID = ab.ID
GROUP BY aaf.adID HAVING TotalFormat >=2
SQL Demo: http://sqlfiddle.com/#!2/9f0ab/10

Categories