Combining columns of the same name - php

So I have a two tables which somehow have the same column name. In the result query, i wish to combine the result which would then occupy the one that are empty.
Here is the structure of my tables:
position
accounts
employees
students
ssc
names
offices
This is my code:
SELECT app.approved, p.position, n.fname, n.mname, n.lname, o.office,
e.signature, ssc.signature
FROM approvals app
LEFT JOIN positions p ON p.position_id = app.position_id
LEFT JOIN accounts a ON a.account_id = app.account_id
LEFT JOIN employees e ON e.account_id = a.account_id
LEFT JOIN students s ON s.account_id = a.account_id
LEFT JOIN ssc ON ssc.students_id = s.students_id AND ssc.removed = 0
LEFT JOIN names n ON n.name_id = s.name_id OR n.name_id = e.name_id
LEFT JOIN offices o ON o.office_id = p.office_id
WHERE app.event_id = '10'
The actual result is this:
Notice that the some rows of e.signature are empty and the same for ssc.signature, so I wish to combine them, by the way, the SSC can never have its signature in the employees table.

Since you know the name of those columns that you wish to combine, you need to use the MySQL COALESCE() function to return the first non null value found in the list of provided arguments.
SELECT COALESCE(NULL, NULL, NULL, 'Aquaman', NULL, 'Some other dude');
This will return Aquaman.
In practice, you can use column names instead of raw values. For example:
SELECT app.approved, COALESCE(e.signature, ssc.signature) AS signature;
Note that the AS signature part is not necessary but it should that you can choose an alias for the combined field.

If the column name is the same then you can use the alias.
SELECT
p.column1 as p_column1,
p.product_name as p_product_name ,
s.product_name as s_product_name
FROM products p INNER JOIN suppliers s
For more info: http://www.mysqltutorial.org/mysql-alias/

Related

INNER JOIN in mysql php

I have a little problem with INNER JOIN in mysql query. I have two tables the first is 'kontrola' and 2nd is 'naruszenia' In 'kontrola' table I have rows:
id
podmiot
miasto
wszczeto
zakonczono
naruszenie_id (Foreign KEY on 'naruszenia' table)
In my naruszenia table I have:
id
naruszenia
Now I want to display using INNER JOIN the naruszenie from 'naruszenia' table.
I've create somethin linke this:
$listakontroli = $connecting->query("SELECT * FROM kontrola INNER JOIN naruszenia ON
kontrola.naruszenie_id=naruszenia.id");
But the result is that when I want to display records in table I have changed the ID of first table(kontrola) and the naruszenia_id still showing id from naruszenia table. How to change it to display properly the word not id.
You could use explicit column name and refer to both the table (in this case using k an n) eg:
$listakontroli = $connecting->query("SELECT k.id
, k.podmiot
, k.miasto
, k.wszczeto7
, k.zakonczono
, n.naruszenia
FROM kontrola k
INNER JOIN naruszenia n ON k.naruszenie_id=n.id");
You need to use LEFT OUTER JOIN or separate the ID from the two tables. e.g.
$listakontroli = $connecting->query("SELECT kontrola.id as kid, naruszenia.id as nid, podmiot, miasto, etc* FROM kontrola INNER JOIN naruszenia ON kontrola.naruszenie_id=naruszenia.id");
This way you can properly distinguish the displayed IDs

Joins from same table

I am trying to join the same table "travel_plan" twice, as the value(s) I need are location_from & location_to in which I can then join the value to my cities table to grab the city name.
SELECT * FROM travel_plan
LEFT JOIN Cities ON Cities.CityID = travel_plan.location_to AS plan_to
LEFT JOIN Cities ON Cities.CityID = travel_plan.location_from AS plan_from
LEFT JOIN user_table ON travel_plan.user_id = user_table.id
ORDER BY date_from DESC LIMIT 0,4") or die(mysql_error());
You need to use table aliases correctly when you're joining the same table more than once, as you're doing with Cities in this query.
SELECT *
FROM travel_plan AS tr
LEFT JOIN Cities AS C1 ON C1.CityID = tr.location_to
LEFT JOIN Cities AS C2 ON C2.CityID = tr.location_from
LEFT JOIN user_table AS us ON tr.user_id = us.id
ORDER BY date_from DESC
LIMIT 0,4
The way you wrote your query, the LEFT JOIN AS clauses were misplaced and not used for qualifying the column names.
This use of SELECT * is really suboptimal, however. From this four-table JOIN, SELECT * kicks back lots of columns with duplicate names, which fouls up _fetch_assoc() methods in php.
Your best bet is to enumerate the columns you fetch, and provide aliases so they don't end up with the same names. I don't know the names of your columns so I have to guess, but it would go something like this.
SELECT us.name, us.id AS userid,
C1.cityname AS to_cityname,
C2.cityname AS from_cityname,
FROM ....
Then you'll find the values in $result['from_cityname'] after you fetch each row.
You misuse the AS keyword, it can be only used in the select part of the query (before FROM), or optionally as alias for table references. But not in the ON part of a join. I guess what you want is:
SELECT *, c1.City as toCity, c2.City as fromCity FROM travel_plan LEFT JOIN Cities c1 ON c1.CityID = travel_plan.location_to LEFT JOIN Cities c2 ON c2.CityID = travel_plan.location_from LEFT JOIN user_table ON travel_plan.user_id = user_table.id ORDER BY date_from DESC LIMIT 0,4
Now you can access the the column aliases toCity and fromCity in your resultset, even though the the original column names are the same.

MySQL Inner Join, selecting from multiple tables

I'm really struggling to get my head around this. I am trying to run a SELECT query from multiple tables.
This is what I have so far that doesn't work;
SELECT jira_issues.*, session_set.* FROM jira_issues, session_set
INNER JOIN reports on jira_issues.report_id = reports.id
WHERE jira_issues.report_id = 648
I have other tables (session_set, report_device) which has a ReportID and report_id column respectively.
I have a report table which has a Primary Key id. In the other tables the report.id key is linked with foreign keys.
Ultimately what I am trying to achieve is this:
I have an entry in the reports table with an id of 648. In the other tables (jira_issues, report_device, session_set), I also have entries which has a foreign key linked to the report id in the report table.
I want to run one SELECT Query to query the tables (jira_issues, report_device and session_set) and get all the data from them based on the report.id.
Thanks!
What about this:
SELECT * FROM jira_issues ji
LEFT JOIN session_set ss ON ji.report_id = ss.ReportID
LEFT JOIN report_device rd ON rd.report_id = ji.report_id
WHERE ji.report_id = 648;
Just say "no" to commas in the from clause. Always use explicit join syntax:
SELECT ji.*, session_set.*
FROM jira_issues ji inner join
reports r
on ji.report_id = r.id inner join
session_set ss
on ss.ReportId = r.report_id
WHERE ji.report_id = 648;
If some of the tables might have no corresponding rows, you might want left outer join instead of inner join.
Kindly try this out. You may get syntax error.
SELECT a., b. FROM jira_issues a, session_set b, reports c
Where a.report_id = c.id and b.report_id = c.id AND a.report_id = 648

Search keyword and apply filters

I am encountering a problem I cannot bypass by myself and I that's why I am posting this question. There are a lot of other posts out there that give me half of the answer and I don't really know how to get it done.
I have 3 tables that contain informations about an ad. One table is "ad_names", another is "ad_locations" and the last one is "ad_details".
Ad_Names has : ad_title, ad_description, ad_date_added
Ad_Locations has : ad_country, ad_region, ad_city
Ad_Details has : ad_price, ad_author, ad_active
Basically I want apply location and details filters for an ad with a certain title.
For example, I want to search "food" keyword in ad-titles and then apply filters like "only from Kansas" or "Only from Kansas + price higher than 500USD". How do I do it?
first you will need to join the tables. do you know if you have a foreign key on the tables? like is there an Ad_ID field on all 3 tables? if the tables are large you may also want to index the fields you are searching. once you have all the data you will "filter" it with a where clause.
http://www.w3schools.com/sql/sql_where.asp
select * from ad_names as A
join ad_location as L on A.key=L.key
join ad_details as D on A.key=D.key
where A.ad_title like '%food%' and L.ad_region = 'Kansas' and D.ad_prics > 500;
depending on how your database is setup, you may get a cartesian result there, so you would have to look at your join. maybe a left outer join limiting the join in an on statement instead of in the where. it is hard to say without more information.
Join types
Assuming that Ad is a table with primary key id, which is a foreign key in each of the other tables (ad_id) then something along the lines of:
Location:
SELECT *
FROM Ad A
INNER JOIN Ad_Names N ON N.ad_id = A.id
INNER JOIN Ad_Locations L ON L.ad_id = A.id
INNER JOIN Ad_Details D ON D.ad_id = A.id
WHERE N.ad_title LIKE '%food%' AND L.ad_city = 'Kansas'
Price and location:
SELECT *
FROM Ad A
INNER JOIN Ad_Names N ON N.ad_id = A.id
INNER JOIN Ad_Locations L ON L.ad_id = A.id
INNER JOIN Ad_Details D ON D.ad_id = A.id
WHERE N.ad_title LIKE '%food%' AND L.ad_city = 'Kansas' AND D.ad_price > 500

MYSQL - JOIN the 1 table or the other table depending if there is a match

I have a table called events and I am doing a select on this table to display a grid with the select results.
The events table has a column called s_code. The s_code value comes from either the suppliers or members table.
How would I do a single JOIN that checks the suppliers and members table to get the code's name without having to do a LEFT JOIN on both members and suppliers tables like my query below. Basically I only want to have b.s_name where I have both b.s_name and c.s_name at the moment.
SELECT a.s_id, b.s_name, c.s_name, a.s_date,
a.s_description, d.s_name, a.s_actiondate,
e.s_name, a.s_emailed, a.s_status
FROM events AS a
LEFT JOIN members AS b ON a.s_code = b.s_code
LEFT JOIN suppliers AS c ON a.s_code = c.s_code
LEFT JOIN webuser AS d ON a.s_userid = d.s_ai
LEFT JOIN webuser AS e ON a.s_actionuserid = e.s_ai
WHERE a.s_status = 'A'
AND a.s_userid = '1'
AND a.s_transactionstatus = 'A'
Just coalesce the two columns into one, if the first is non null return that, otherwise the second;
SELECT a.s_id, COALESCE(b.s_name, c.s_name) s_name, a.s_date, ...

Categories