SQL inner join of multiple tables and search through database - php

I'm making a search function in PHP and I have three tables that I wish to join to a single one; the three tables looks as follow:
band
ID | bands
---+----------
1 | Muse
2 | Coldplay
3 | etc.
release
ID | releases
---+----------
1 | Showbiz
2 | Origin of Symmentry
3 | etc.
track
ID | tracks
---+-----------
1 | Sunburn
2 | Muscle Museum
3 | etc.
I want these tables to be put into this:
discografic
ID | band_id | release_id | track_id
---+----------+-------------+---------
1 | 1 | 1 | 1
2 | 1 | 1 | 2
3 | etc.
So that the table with the SQL code looks like this:
discografic
ID | bands | releases | tracks
---+----------+-------------+---------
1 | Muse | Showbiz | Sunburn
2 | Muse | Showbiz | Muscle Museum
3 | etc.
I want to INNER JOIN these tables. I joined one but I can't really figure out how the get the last joined as well.
SELECT *
FROM band
INNER JOIN discografic
ON band.id = discografic.band_id
This should probably have its own question; I also want to be able to search this database, but only have the result show up once, and also reference to the band every time. For example, if I search "Showbiz" it will give me "Muse", and only show it once.
Note: This is for testing purposes only, security is none of my concerns.

Try with this query:
select d.id,b.bands,r.releases,t.tracks from discografic as d INNER JOIN band as b on
d.band_id=b.id INNER JOIN release as r on d.release_id=r.id INNER JOIN track as t on
d.track_id=t.id GROUP BY d.id

Try This query
Select a.ID,b.bands,c.releases,d.tracks from discografic as a
inner join band as b on a.band_id = b.ID
inner join release as c on a.release_id = c.ID
inner join track as d on a.track_id = d.ID
where b.bands = 'Muse'

Use this query to insert the data like you wanted:
Insert into discograpy
(id,bands,releases,tracks)
SELECT band.ID,bands,releases,tracks
FROM band
INNER JOIN releases
ON band.id = releases.id
inner join track
on band.id = track.id
Use this query to show you only one band:
Declare #releases varchar(50)
Set #releases = 'showbiz'
SElect distinct bands from discograpy where releases = #releases
Here any variable can be passed or set in place of showbiz. This is an example

Related

how can select 3 records of foreign key with join in sql

I'm sorry for my poor English .
I have a table for project registration : like
Type of service | Total Amount | prepayment | last payment | Cost of tolls
web design | 1000 | 1 (F-key) | 2 (F-key) | 3 (F-key)
The second table for the status of payment and amount
id | amount | Payment status | Description
1 | 400 | yes | for prepayment
2 | 600 | no | for last payment
3 | 0 | no | for Cost of tolls
Now my question is : How can I join two tables And pull out all THAT three columns ?
I've pulled out the prepayment column with this code
SELECT mzmx_request.service, mzmx_request.amount,
(mzmx_payment.payment) as prepayment,
(mzmx_payment.status) as prepayment_status
FROM mzmx_request
JOIN mzmx_payment ON mzmx_request.prepayment = mzmx_payment.id
How do I add two more columns?
JOIN mzmx_payment ON mzmx_request.payment = mzmx_payment.id
JOIN mzmx_payment ON mzmx_request.pay_more = mzmx_payment.id
Just join three times. You already did it once. For example:
SELECT
r.service,
r.amount,
pp.payment as prepayment,
pp.status as prepayment_status,
lp.payment as last_payment,
lp.status as last_payment_status,
ct.payment as cost_of_tolls,
ct.status as cost_of_tolls_status
FROM mzmx_request r
left JOIN mzmx_payment pp ON r.prepayment = pp.id
left JOIN mzmx_payment lp ON r.lastpayment = lp.id
left JOIN mzmx_payment ct ON r.costoftolls = ct.id
Since you are joining three times against the same table you'll need to alias the table. In this case I used the aliases pp, lp, and ct for prepayment, last payment, and cost of tolls respectively.
3 referenced fields are independent - so they needs in independent ref table copies:
SELECT *
FROM main
JOIN slave AS slave1 ON main.prepayment = slave1.id
JOIN slave AS slave2 ON main.last_payment = slave2.id
JOIN slave AS slave3 ON main.cost_of_tolls = slave3.id

Joining table mysql -- without double iteration

Let me start by saying this should be a relatively simple problem which is / was made unnecessary complicated by bad Database design (not by me) that said im also no expert in mysql.
Consider the following
Table Schedule
Note how the columns homeID and visitorID contains the names of the teams and not the actual teamID's
In a bid to fix this I created a new table with columns containing teamID AND teamName as can be seen by below image.
Table Teams
My Problem(s)
I must get the teamID from table Teams for BOTH home team AND away team
So I created the Teams table and this simple script:
SELECT schedule.*, teams.*
FROM schedule
JOIN teams ON schedule.homeID = teams.teamName OR schedule.visitorID = teams.teamName
WHERE schedule.gameID = 411
LIMIT 1 #added Limit1 else the code generates to rows
Output of mysql Script
Limit 1
Notice above how teamID is only generated for 1 team with Limit 1
No Limit Statement (Double Iteration)
Notice above how teamID can get retrieved for BOTH teams. Problem is its doing a double iteration.
TLDR; The above presents the following problems
Firstly the script will generate two outputs one for home team and once for away team. As to be expected however I cant have that.
As a workaround to Problem number 1 -- I added Limit 1 the problem I get with Limit though is that it only gives back a single teamID (as to be expected, I guess)
Question
How can I get BOTH teamID's from table teams with a single iteration? Hope this make sense....
Extra
A demo of application with hard coded team names looks like this (just to give an idea of what they are trying to achieve)
Sounds like you want to join teams twice to schedule.
SELECT s.*,
th.*,
ta.*
FROM schedule s
INNER JOIN teams th
ON s.homeid = th.teamname
INNER JOIN teams ta
ON s.visitorid = ta.teamname
WHERE s.gameid = 411;
I guess that you want to show both team in one row instead of two rows.
If yes, then you need to join the table teams twice.
Consider this demo: http://www.sqlfiddle.com/#!9/bb5e61/1
This join will collect both teams into one row:
SELECT s.*,
t1.teamId as homeId_teamId,
t1.teamCode as homeId_teamCode,
t1.teamName as homeId_teamName,
t2.teamId as visitorId_teamId,
t2.teamCode as visitorId_teamCode,
t2.teamName as visitorId_teamName
FROM Schedule s
JOIN Teams t1 ON s.homeId = t1.teamName
JOIN Teams t2 ON s.visitorId = t2.teamName;
| id | homeId | visitorId | homeId_teamId | homeId_teamCode | homeId_teamName | visitorId_teamId | visitorId_teamCode | visitorId_teamName |
|----|--------|-----------|---------------|-----------------|-----------------|------------------|--------------------|--------------------|
| 1 | Poland | Colombia | 1 | PL | Poland | 2 | CO | Colombia |
However you can also consider LEFT joins instead on INNER joins, which will work in a case where there is no relevant data in the TEAMS table:
SELECT s.*,
t1.teamId as homeId_teamId,
t1.teamCode as homeId_teamCode,
t1.teamName as homeId_teamName,
t2.teamId as visitorId_teamId,
t2.teamCode as visitorId_teamCode,
t2.teamName as visitorId_teamName
FROM Schedule s
LEFT JOIN Teams t1 ON s.homeId = t1.teamName
LEFT JOIN Teams t2 ON s.visitorId = t2.teamName;
| id | homeId | visitorId | homeId_teamId | homeId_teamCode | homeId_teamName | visitorId_teamId | visitorId_teamCode | visitorId_teamName |
|----|----------|-----------|---------------|-----------------|-----------------|------------------|--------------------|--------------------|
| 1 | Poland | Colombia | 1 | PL | Poland | 2 | CO | Colombia |
| 3 | Ya Majka | Poland | (null) | (null) | (null) | 1 | PL | Poland |
| 2 | Ya Majka | Rossija | (null) | (null) | (null) | (null) | (null) | (null) |
Here are the scripts that make up the tables from the examples
CREATE TABLE Schedule(
id int, homeId varchar(20),visitorId varchar(20)
);
INSERT INTO Schedule VALUES
(1, 'Poland', 'Colombia' ),(2,'Ya Majka','Rossija'),
(3,'Ya Majka','Poland');
CREATE TABLE Teams(
teamId int, teamCode varchar(10), teamName varchar(20)
);
INSERT INTO Teams VALUES
(1, 'PL', 'Poland' ),(2,'CO','Colombia'),(3,'US','United States');
You can use a subquery (two of them in the same query) to solve this:
select
gameID,
weekNum,
gameTimeEastern,
(select teamName from teams where teamID = schedule.homeID) as homeName,
homeScore,
(select teamName from teams where teamID = schedule.visitorID) as visitorName,
visitorScore from schedule;
This doesn't get all the columns from schedule, just an example to show how it works. If you need various queries (including select *, though this isn't a good practice except for testing), you could create a view based on a query like the above (with ALL columns from schedule, except homeID and visitorID that get replaced with sub-queries from the teams table). Then you can place queries against that view - and they will work like the original table where you had team names directly in it.

Display Highest Offer, But Still Display With No Offer

I'm trying to display businesses along with their highest discount offer. But I still would like to display businesses with no offer.
Businesses are stored in business_tb
business_id | business_name
------------+---------------
1 | aaa
2 | bbb
3 | ccc
offered discounts by those businesses are stored in deal_offer_tb
deal_offer_id | business_id | deal_id
--------------+-------------+----------
1 | 1 | 3
2 | 1 | 2
3 | 2 | 0
4 | 1 | 1
5 | 3 | 3
and types of discounts are stored in deal_tb.
deal_id | discount
--------+----------
1 | 40%
2 | 30%
3 | 20%
4 | 10%
So the display I wanted should look something like this:
1 | aaa | 40%
2 | bbb | ---
3 | ccc | 20%
But with my current query:
SELECT a.business_id, a.business_name, c.discount
FROM business_tb a
LEFT JOIN (SELECT min(deal_id) AS deal_id, business_id FROM deal_offer_tb GROUP BY business_id) b ON a.business_id = b.business_id
LEFT JOIN deal_tb c ON b.deal_id = c.deal_id
I only get:
1 | aaa | 40%
3 | ccc | 20%
It does not display businesses with no offered discounts.
How am I suppose to get my desired output?
UPDATE: I don't know what happened earlier, but my query is working the way I wanted it. Thanks to the effort of those who answered. Appreciate it, big time!
I would approach this by using a subquery to find the greatest discount for each business, joining the deal_offer_tb and deal_tb tables. Then, join this subquery to the business_tb table to get the final result. Note that I use an initial LEFT JOIN to account for that a given business may not even have an deals associated with it. In that case, I assign a maximum discount of 0 to that business (which makes sense, since then the full regular price would apply).
SELECT
t1.business_id,
t1.business_name,
COALESECE(t2.max_discount, 0) AS max_discount
FROM business_tb t1
LEFT JOIN
(
SELECT t1.business_id, MAX(t2.discount) AS max_discount
FROM deal_offer_tb t1
INNER JOIN deal_tb t2
ON t1.deal_id = t2.deal_id
GROUP BY t1.business_id
) t2
ON t1.business_id = t2.business_id
This query is essentially your query (with table aliases):
SELECT b.business_id, b.business_name, d.discount
FROM business_tb b LEFT JOIN
(SELECT MIN(deal_id) AS deal_id, business_id
FROM deal_offer_tb dot
GROUP BY business_id
) dot
ON b.business_id = dot.business_id LEFT JOIN
deal_tb d
ON d.deal_id = dot.deal_id;
By the definition of LEFT JOIN, it will keep all rows in business_tb, regardless of whether or not there are matches in the rest of the FROM clause. You have no additional filtering (via WHERE) or aggregation. Hence, this should returns all the rows in business_tb.
Below is one way to do the query:
SELECT
a.business_id, a.business_name, b.max
FROM business_tb a
INNER JOIN (
SELECT
c.business_id, MAX(d.discount) AS max
FROM deal_offer_tb c
LEFT JOIN deal_tb d ON c.deal_id = d.deal_id
GROUP BY c.business_id
) b ON a.business_id = b.business_id;
You don't have deal_id 0 in deal_tb, so I assume it's null for deal_offer_id 3.

Mysql - join 2 queries with limit

Im not very familiar with using 'join' in queries. I really tried solving this by my own, but it seems to be too hard.
I got 2 Tables:
Table 'users':
+-----------------+-----------------+
| member | online |
+-----------------+-----------------+
| mahran | 1 |
| peter | 1 |
| Jen | 1 |
| Steve | 0 |
+-----------------+-----------------+
Table 'tickets'
+-----------------+----------------+----------------+
| name | category | time |
+-----------------+----------------+----------------+
| mahran | silver | 1 |
| peter | blue | 1 |
| mahran | blue | 2 |
| peter | red | 3 |
| peter | green | 2 |
| Jen | silver | 1 |
+-----------------+----------------+----------------+
The chellange:
I need each member (users.member) who's online (users.online). The next thing is to get the category for each member (user.member = tickets.name) with the highest time (probably ORDER BY time DESC LIMIT 1).
So, for example:
Peter is online. Peters highest time is 3 at the position of category=red. So I want peter to show up in the result with his category 'red'. Mahran would show up with blue. Jen would get silver. And steve would be left out because he's not online.
I hope this was clear. In general I know how the queries would look like but theres no chance for me merging them together.
What needs to be merged:
SELECT member FROM users WHERE online = 1;
|
v for each member
SELECT category FROM tickets WHERE name=users.member ORDER BY time DESC.
So, any ideas how to solve this?
Here is a fiddle with a not working query: Click
You can do this easily with a correlated subquery:
select u.member,
(select t.category
from tickets t
where t.name = u.member
order by t.time desc
limit 1
) as MostRecentCategory
from users u
where u.online = 1;
This can make use of the following indexes: users(online, member) and ticket(member, time, category).
Here is the query you're looking for:
SELECT U.member
,T.category
FROM users U
INNER JOIN tickets T ON T.name = U.member
INNER JOIN (SELECT T2.name
,MAX(T2.time) AS [maxTime]
FROM tickets T2
GROUP BY T2.name) AS M ON M.name = T.name
AND M.maxTime = T.time
WHERE U.online = 1
The use of [name] to join the two tables is not a good practice, it's much better to use keys instead. But my query is just here to help you understanding the process of jointure.
Hope this will help you.
If i understand you correctly
SELECT DISTINCT users.member, tickets.category FROM tickets JOIN users ON users.member = tickets.name WHERE users.online = 1 ORDER BY tickets.time DESC
Can you make sql fiddle?
USE DISTINCT
stackoverflow.com/questions/11704012/mysql-distinct-join
try this
SELECT DISTINCT User.member,Ticket.category FROM users AS USER
INNER JOIN tickets AS Ticket ON (User.member = Ticket.name)
WHERE User.online = 1;
Sorry, but peter seems to be RED, It's time is 3. Don't you?
Depending on table definition, is not guaranteed to have one only result for each user.
For example, if peter has time 3 in two categories, you can get one different category depending of the SQL sorting method.
To be sure, tickets.Category and tickets.time must be in a unique key (both toghether, not a unike key for each field)
Assuming that, the Query could be this.
select t2.name, t2.category
from
tickets t2
INNER JOIN (Select
u.member, max(time)
from users u, tickets t
where
u.member = t.name
and u.online = 1
group by u.member
) as usermaxtime on t2.name = usermaxtime.member;

Select from two tables where rows from second table should be shown as columns in first

I have two tables in MySQL:
Table entry:
id | name | date
1 | Test Entry | 12/12/2013
2 | Test Entry 2 | 12/12/2013
Table note
id | entry_id | name | value
1 | 1 | note1 | value1
2 | 1 | note2 | value2
3 | 2 | note1 | value1
4 | 3 | note4 | value4
Where entry_id in note is a foreign key to id in entry.
Is there any solution I can create with a SELECT that will give me a result like the following?
entry_id | name | note1 | note2 | note3
1 | Test Entry | value1 | value2 | -
2 | Test Entry 2 | value 1 | - | value3
I want to avoid LEFT JOIN here (current implementation is working like this) and want to join note only once if that is possible. LEFT JOIN is not good here, because I do not know how many notes can be attached to one entry. My current implementation works that way that I first fetch all distinct notes by name that can be found in note, and then build a SELECT with foreach through PHP. Finally, the SELECT statement looks like this:
SELECT
E.id as entry_id,
E.name as name,
N1.value as note1_value,
N2.value as note2_value,
N3.value as note3_value
FROM entry E
JOIN LEFT note N1 ON E.id = N1.entry_id AND N1.name = 'note1'
JOIN LEFT note N2 ON E.id = N2.entry_id AND N2.name = 'note2'
JOIN LEFT note N3 ON E.id = N3.entry_id AND N3.name = 'note3'
Things get tricky when I join on note 20-30 times.
No, there is not a way to do that without joins.
I would recommend doing 2 queries.
select * from entry where id = id
select * from note where entry_id = id
and then join the results in your application code. You're right, the left joins are going to be bad.
Best would be to use a table with one note value and a note type (number) per each line.
id | value | note_no
Like this you can use as much notes as you like.
You can get the notes on one line using group_concat.
For an example, see here: http://lietoservetruth.wordpress.com/2010/12/13/mysql-group_concat-vertival-concat-concat-records/
This is faster than asking DB twice, and it's better DB design...

Categories