MySQL Query for Team Schedule - php

I am trying to retrieve schedules for each team based on my table below, but I am having some trouble getting the team names to display. Here are my tables:
TEAM
(team_id,
team_name,
team_mascot,
etc.)
GAME
(game_id,
game_date,
game_home_team,
game_visitor_team,
game_home_score,
game_visitor_score,
game_complete)
Here is my current query. I am able to get the team's id values with this but I need the team names as id values won't do me much good.
SELECT game_home_team, game_visitor_team, game_date
FROM game
INNER JOIN team home ON home.team_id = game_home_team
INNER JOIN team visitor ON visitor.team_id = game_visitor_team
WHERE game_home_team = ?
OR game_visitor_team = 6
ORDER BY game_date ASC;
How can I retrieve the team names with this query and also display a result such as W or L depending on the score for the game? Thanks so much in advance.

SELECT
home.team_name AS home_team,
visitor.team_name AS visitor_team,
game_date,
IF(
game_home_score = game_visitor_score,
'Tie',
IF(
game_home_score > game_visitor_score,
'Hometeam',
'Visitorteam'
)
) AS Winner
FROM game
INNER JOIN team home ON home.team_id = game_home_team
INNER JOIN team visitor ON visitor.team_id = game_visitor_team
WHERE game_home_team = ?
OR game_visitor_team = 6
ORDER BY game_date ASC;

select game_home_team, home.team_name AS homename,
game_visitor_team, visitor.team_name AS visitorname
etc...

Related

How to count records in MySQL and merge results in PHP

I have a table which stores clients like this:
id name
-- ----
1 John
2 Jane
...
I also have another table which stores links created by clients:
id client_id link created
-- --------- ---- -----------
1 1 ... 2015-02-01
2 1 ... 2015-02-26
3 1 ... 2015-03-01
4 2 ... 2015-03-01
5 2 ... 2015-03-02
6 2 ... 2015-03-02
I need to find how many links a client has created today, this month and during all the time. I also need their name in the result, so I'll be able to craete a HTML table to display the statistics. I thought I can code as less as possible like this:
$today = $this->db->query("SELECT COUNT(*) as today, c.id as client_id, c.name FROM `links` l JOIN `clients` c ON l.client_id = c.id WHERE DATE(l.created) = CURDATE() GROUP BY c.id");
$this_month = $this->db->query("SELECT COUNT(*) as this_month, c.id as client_id, c.name FROM `links` l JOIN `clients` c ON l.client_id = c.id WHERE YEAR(l.created) = YEAR(NOW()) AND MONTH(l.created) = MONTH(NOW()) GROUP BY c.id");
$yet = $this->db->query("SELECT COUNT(*) as yet, c.id as client_id, c.name FROM `links` l JOIN `clients` c ON l.client_id = c.id WHERE GROUP BY c.id");
And then merge them in PHP as I asked HERE before, like this:
$result = array_replace_recursive($today, $this_month, $yet);
So I'll be able to loop into the result and print my HTML table.
But there are logical problems here. Everything works fine, but the result in a month is a wrong number, forexample the whole created links of one person is 1 but it shows 4 in the monthly counter! I also tried to use RIGHT JOIN in SQL query to get all clients, so array_replace_recursive in PHP could work fine as I think it doesn't work properly at the moment, but no success and got wrong results again.
Can anyone show me a way to make the job done?
This query should do it for today
$query_today="
SELECT name, id AS user_id, (
SELECT COUNT( * )
FROM links
WHERE client_id = user_id AND created = '2015-03-02'
) AS alllinks
FROM clients"
adjust the WHERE clause in the subquery for months and all
$query_month="
SELECT name, id AS user_id, (
SELECT COUNT( * )
FROM links
WHERE client_id = user_id AND created like '2015-03%'
) AS alllinks
FROM clients"
$query_all="
SELECT name, id AS user_id, (
SELECT COUNT( * )
FROM links
WHERE client_id = user_id
) AS alllinks
FROM clients"

How to get the select the sum of a column JOINing with another table where elementxof table1 = elementx of table2?[special case]

I have two tables named videos and rating.
The first table
videos
uploader video_id
james ac0255
james ue2145
isabell qw2378
The second table:
rating
video_id score
ac0255 4
qw2378 2
ue2145 6
I want to store in variable x the sum of the score of all the videos uploaded by james.
Can anyone suggest an SQL query for it?
Try with this:
SELECT SUM(rating.score)
FROM videos
INNER JOIN rating
ON videos.uploader = rating.video_id
WHERE videos.uploader = 'james';
A simple join will do.
SELECT sum(r.score)
FROM videos v
JOIN rating r ON (v.video_id = r.video_id)
WHERE v.uploader = 'james';
In order to get the sum of score for James , you need to use JOINS and SUM function of mysql
SELECT SUM(Rating.score)
FROM videos as Videos
INNER JOIN rating AS Rating
ON Videos.uploader = Rating.video_id
WHERE Videos.uploader = 'james';

Combining two SQL queries PDO

I'm quite stuck on the following issue. I have a series of tables:
What I want to do is get all the information on a room, assuming that the amount of bookings don't exceed the room number available for that Room.
So to get my Room details my SQL is this:
SELECT Rooms.RoomID as RoomID,
RoomName, NumOfRooms,
MaxPeopleExistingBeds,
MaxExtraBeds,
MaxExtraPeople,
CostPerExtraPerson,
MaximumFreeChildren,
IncludeBreakfast,
MinRate
FROM Rooms, RoomDetails
WHERE Rooms.AccommodationID = :aid AND
Rooms.RoomID = RoomDetails.RoomID
GROUP BY RoomName
Which upon return gets me a list of details for those rooms as follows:
I then use this query to get the number of bookings, and the ID of the room:
SELECT Booking.RoomID,
count(Booking.RoomID) as Bookings
FROM Booking
WHERE ArriveDate >= :aDate AND
DepartDate <= :dDate AND
AccommodationID = :aid
GROUP BY RoomID
I then combine both and feed the two arrays back in one array using this function:
public function get_availability($aid, $aDate, $dDate) {
$stmt = $this->db->prepare('SELECT Rooms.RoomID as RoomID, RoomName, NumOfRooms, MaxPeopleExistingBeds, MaxExtraBeds, MaxExtraPeople, CostPerExtraPerson, MaximumFreeChildren, IncludeBreakfast, MinRate FROM Rooms, RoomDetails WHERE Rooms.AccommodationID = :aid AND Rooms.RoomID = RoomDetails.RoomID GROUP BY RoomName');
$stmt->bindValue(':aid', $aid);
$stmt->execute();
$rooms = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt2 = $this->db->prepare('SELECT Booking.RoomID, count(Booking.RoomID) as Bookings FROM Booking WHERE ArriveDate >= :aDate AND DepartDate <= :dDate AND AccommodationID = :aid GROUP BY RoomID');
$stmt2->bindValue(':aid', $aid);
$stmt2->bindValue(':aDate', $aDate);
$stmt2->bindValue(':dDate', $dDate);
$stmt2->execute();
$bookings = $stmt2->fetchAll(PDO::FETCH_ASSOC);
$room = array($rooms, $bookings);
return (!empty($room)) ? $room : false;
}
The thing is, what I actually want to do is only return the room details where NumOfRooms is less than the number of Bookings.
So for instance where I have $bookings, if it tells me that for room ID 4, I have 3 bookings for a set period, and my NumOfRooms is 1. Then I know that I have no capacity that week to take any more bookings on. If however I have 1 booking and one capacity then that is still full. But if I have NumOfRooms of 2, and bookings amount to 1, I know I have room.
So basically if NumOfRooms > BookingCount then the room is available.
How can I amalgamate both queries and simplify my code to make this possible?
I.E to put it simply, how do I select all of the info from RoomDetails given an ArriveDate in Booking and a DepartDate and a RoomID, where NumOfRooms > count(Booking.RoomID) (Where it is within those dates and the room id is equal to the room id of Rooms).
Your problem can be solved by simply updating the SQL statement itself:
SELECT r.RoomID AS RoomID,
RoomName,
NumOfRooms,
MaxPeopleExistingBeds,
MaxExtraBeds,
MaxExtraPeople,
CostPerExtraPerson,
MaximumFreeChildren,
IncludeBreakfast,
MinRate
FROM Rooms r
JOIN RoomDetails rd
ON r.RoomID = rd.RoomID
JOIN (
SELECT b.RoomID,
AccommodationID,
count(b.RoomID) AS Bookings
FROM Booking b
WHERE ArriveDate >= :aDate
AND DepartDate <= :dDate
GROUP BY RoomID
) t
ON t.AccommodationID = r.AccommodationID
WHERE r.AccommodationID = :aid
AND t.Bookings < NumOfRooms
GROUP BY RoomName
You can select out all of the booking counts per room for the desired date range as a subquery, and then LEFT JOIN that subquery against the list of your rooms filtered by your desired AccommodationID and the desired NumOfRooms > BookingCount criteria. The key here is in the join type used for this subquery, as an inner join would limit your results to only rooms that actually had bookings.
SELECT Rooms.RoomID as RoomID,
RoomName, NumOfRooms,
MaxPeopleExistingBeds,
MaxExtraBeds,
MaxExtraPeople,
CostPerExtraPerson,
MaximumFreeChildren,
IncludeBreakfast,
MinRate,
BookingCount
FROM Rooms
INNER JOIN RoomDetails on Rooms.RoomID = RoomDetails.RoomID
LEFT JOIN (
SELECT Booking.RoomID,
count(Booking.RoomID) as BookingCount
FROM Booking
WHERE ArriveDate >= :aDate AND
DepartDate <= :dDate
GROUP BY Booking.RoomID
) RoomBookings ON Rooms.RoomID = RoomBookings.RoomID
WHERE Rooms.AccommodationID = :aid
AND NumOfRooms > BookingCount
GROUP BY RoomName

Inner join with 3 tables

I'm working with PHP and PDO, and I need to recolect information joining 3 tables:
photos
albums
album_photos
The table have the following structure:
photos:
photo_id (int)
path (varchar)
nick (varchar)
date (timestamp)
albums
album_id (int)
album_name (varchar)
nick (varchar)
date (timestamp)
album_photos
album_id (int)
photo_id (int)
nick (varchar)
date (timestamp)
So, I want to show all the albums with a max of 5 photos for each one, where the user nick is 'owner'.
To be shown as follows:
album_name_1:
[photo_1]
[photo_2]
[photo_3]
[photo_4]
[photo_5]
album_name_2:
[photo_1]
[photo_2]
[photo_3]
[photo_4]
[photo_5]
I only know that something like this can be made with INNER JOIN, but I can't found how I can make it with 3 tables.
There examples or other help that I can get to do this?
SELECT a.*, c.date
FROM Album a
INNER JOIN Album_Photo b
ON a.Album_ID = b.Album_ID
INNER JOIN Photo c
ON b.Photo_ID = c.Photo_ID
WHERE c.Nick = 'owner' AND
(
SELECT COUNT(*)
FROM album_photo d
WHERE b.album_id = d.album_id AND
d.nick = 'owner' AND
b.date >= d.date
) <= 2 // <<== change this value to 5
SQLFiddle Demo
I think this can be resolved using Stored Procedures. Using variables and loops, you can retrieve the records you desire. Getting only a maximum of 5 records from an album is quite challenging when you only use the basic SQL commands. Sometimes, you cannot derive the right records. I suggest you use Stored Proc. :)
Try like
"SELECT albums.*,photos.id,photos.path,photo_date as Pht_date
FROM albums
JOIN album_photos
ON album_photos.album_id = albums.album_id
JOIN photos
ON photos.photos_id = album_photos_id
"
But you cont give individual limit for photos where it involved in "JOIN" orelse you need to give individually like
$album_ids = "SELECT album_id FROM albums";
then for the photos you need to write query liks
"SELECT photos.* FROM photos
WHERE album_photos.album_id in (".$album_ids.") AND album_photos.nick = 'owner'
JOIN album_photos
ON album_photos.photo_id = photos.photos_id
LIMIT 0,10
"

how to get data of maximum date in php

i have three tables..
SEEKER
seeker_nic--- username---request_fulfilled
111-----------ali--------YES
222-----------bilal------YES
second table is
DONOR
donor_nic---username----area
999----------Fahad-------UK
555----------SAJAD------USA
777---------HAMZA-------PK
third table is
STATUS
status-id---seeker_nic---donor_nic--requestfulfilled_by----request_fulfilled_date
1 -------------111-------999---------- Fahad-------------2012/04/09
2 -------------111-------555---------- SAJAD-------------2012/05/15
3--------------222------777-----------HAMZA--------------2012/07/20
now i want this result for SEEKER (111) with latest data..
seeker_nic---username--- request_fulfilled---requestfulfilled_by----area---request_fulfilled_date
111-----------ali--------YES-----------------SAJAD-----------------USA--------2012/05/15
i am trying this query, this query shows rite seeker_nic, and requestfulfilled_date, but it shows wrong donor-nic, area and requestfulfilled_by...
SELECT seeker.seeker_nic, donor.donor_nic, donor.area,
status.requestfulfilled_b , max( status.`request_fulfilled_date` ) AS request_fulfilled_date
FROM seeker
JOIN STATUS ON seeker.seeker_nic = status.seeker_nic
JOIN DONOR ON status.donor_nic = donor.donor_nic
WHERE seeker.username = '$uname'
GROUP BY status.`seeker_nic`
i am getting ans like this....
seeker_nic---username--- request_fulfilled---requestfulfilled_by--------area--------request_fulfilled_date
111-----------ali---------------YES-----------------HAMZA--------------PK------------2012/05/15
plz help me.. :(
Try this:
SELECT seeker.seeker_nic, donor.donor_nic, donor.area, status.requestfulfilled_by, status.request_fulfilled_date
FROM seeker
JOIN (
SELECT seeker_nic, max(request_fulfilled_date) as last_date
FROM status
GROUP BY seeker_nic
) x ON x.seeker_nic = seeker.seeker_nic
JOIN STATUS
ON x.seeker_nic = status.seeker_nic
AND x.last_date = status.request_fulfilled_date
JOIN DONOR
ON status.donor_nic = donor.donor_nic
WHERE seeker.username = '$uname'
If you need to select latest date for one particular user, you do not need a GROUP BY clause:
SELECT
status.request_fulfilled_date, # status.requestfulfilled_by,
seeker.seeker_nic, seeker.username, seeker.request_fulfilled,
donor.donor_nic, donor.username, donor.area
FROM status
LEFT JOIN seeker ON status.seeker_nic = seeker.seeker_nic
LEFT JOIN donor ON status.donoc_nic = donor.donor_nic
WHERE seeker.username = 'ali'
ORDER BY status.request_fulfilled_date DESC
LIMIT 1
SELECT x.seeker_nic, y.username, y.request_fulfilled,
x.requestfulfilled_by, z.area, x.request_fulfilled_date
FROM status x, seeker y, donor z
WHERE x.seeker_nic=y.seeker_nic AND y.seeker_nic=111 AND z.donor_nic=x.donor_nic;

Categories