Mysql Complex Join Query Issue - php

I have 5 mysql tables as described below.
clinics table
id
name
d_location_subscription table
id
clinic_id
t_id //t_id will contain a foreign key of d_cities, d_states or d_countries table
type "country" "state" "city"
d_countries table
id
name
code
d_states table
id
d_country_id
name
code
d_city table
id
d_state_id
name
code
d_location_subscription table is used to record clinic's subscription for a location(it may be a city, state or country). I'm expecting to get all subscribed cities for a specific
clinic using d_location_subscription table.
For example, if clinic A is subscribed to Texas state, I should be able to get all city ids for clinic A.
I created following sql query, it looks ugly but generate a close result what i want to achieve.
select
`d`.`id` AS `clinic_id`,
if((`dct`.`id` is not null),`dct`.`id`,if((`dct1`.`id` is not null),`dct1`.`id`,`dct2`.`id`)) AS `d_city_id`
from ((((((((
`d_location_subscriptions` `dls`
join `clinics` `d`
on((`d`.`id` = `dls`.`clinic_id`)))
left join `d_countries` `dc`
on(((`dc`.`id` = `dls`.`t_id`) and (`dls`.`type` = 'country'))))
left join `d_states` `ds`
on((`ds`.`d_country_id` = `dc`.`id`)))
left join `d_cities` `dct2`
on((`dct2`.`d_state_id` = `ds`.`id`)))
left join `d_states` `ds1`
on(((`ds1`.`id` = `dls`.`t_id`) and (`dls`.`type` = 'state'))))
left join `d_cities` `dct`
on((`dct`.`d_state_id` = `ds1`.`id`)))
left join `d_cities` `dct1`
on(((`dct1`.`id` = `dls`.`t_id`) and (`dls`.`type` = 'city'))))
)
when there is record with type "country" in d_location_subscription table, I receive following result. total number of records returned are equal to the number of d_states table records.
How should I get rid of those Null values by changing above query?
And please advice me if this is the correct way to acheive similar functionality. Thanks in advance :)

The quickest, dirtiest way to achieve what you want is just to append this where condition to your query:
WHERE d_city_id is not null
but you might prefer to rework your query and decide where you really need LEFT joins and not INNER joins

the IF() computed column is in essence what STT LCU was trying to offer, but you can't use that directly in the where for some reason.
I've rewritten your query, but with different aliases to better follow the origination of the tables / relationships to get the data. In the end, I've added a where to test for ANY ONE of the "ID" values as NOT NULL. If they are ALL Null, the record should be excluded..
select
d.id AS clinic_id,
if(CityViaState.id is not null, CityViaState.id,
if( ByCity.id is not null, ByCity.id, CityViaCountry.id )) AS d_city_id
from
d_location_subscriptions dls
join clinics d
ON dls.clinic_id = d.id
left join d_countries ByCountry
ON dls.t_id = ByCountry.id
and dls.type = 'country'
left join d_states StateViaCountry
ON ByCountry.id = StateViaCountry.d_country_id
left join d_cities CityViaCountry
ON StateViaCountry.id = CityViaCountry.d_state_id
left join d_states ByState
ON dls.t_id = ByState.id
and dls.type = 'state'
left join d_cities CityViaState
ON ByState.id = CityViaState.d_state_id
left join d_cities ByCity
ON dls.t_id = ByCity.id
and dls.type = 'city'
where
CityViaState.id is not null
OR ByCity.id is not null
OR CityViaCountry.id is not null

Related

MYSQL PHP select the opposite of a query

I have two tables.
One table has everything I need including a cardId(PK)
The other name is a user type table. This table stores the userId and the cardId(FK).
SELECT ci.cardId, ci.year, ci.name, ci.number
FROM USERCARDS uc
INNER JOIN CARDINDEX ci ON uc.cardId = ci.cardId
WHERE uc.userId = 'USER_ID'
So for this query, it will display the cardId, year, name, and number from the CARDINDEX. It will only display the cards that the user has saved in USERCARDS.
I want to do the opposite. If a user is looking at, lets just say, 5 cards, but the CARDINDEX has 50 cards, this query will display the information for the five cards. However, for a new query, I would want to show the remaining 45 cards. Basically, they cant add a card they already are following.
I tried to have uc.cardId != ci.cardId but that didn't work. Im kind of lost.
You can phrase this as a LEFT JOIN:
SELECT ci.cardId, ci.year, ci.name, ci.number
FROM CARDINDEX ci LEFT JOIN
USERCARDS uc
ON uc.cardId = ci.cardId AND
uc.userId = 'USER_ID'
WHERE uc.cardID IS NULL;
Alternatively, you could write this using `NOT EXISTS:
SELECT ci.cardId, ci.year, ci.name, ci.number
FROM CARDINDEX ci
WHERE NOT EXISTS (SELECT 1
FROM USERCARDS uc
WHERE uc.cardId = ci.cardId AND
uc.userId = 'USER_ID'
);

Double LEFT JOIN with same tables

My sql:
SELECT * FROM ex_pair
LEFT JOIN ex_currency as client
ON client_curr = currency_id
LEFT JOIN ex_currency as company
ON co_curr = currency_id
I need to get data for two currency_id but I have an error
ambiguous column name: 'currency_id'
Is there any way to do it right or i need to use two queries?
You need to include your alias in your join, like this:
SELECT *
FROM ex_pair
LEFT JOIN ex_currency AS client
ON client_curr = client.currency_id
LEFT JOIN ex_currency as company
ON co_curr = company.currency_id
You may also want to do something other than select * as you will have two tables with the same columns - something like
SELECT pair.*, company.currency_id AS company_currency_id, client.currency_id as client_currency_id, [...]
FROM ex_pair AS pair
[...]
This way when you explicitly declare the columns you intend to use from ex_currency with an alias, you can know on the other end more easily which are client and which are company. You will need to do this for each column in the currency table that you want in your result, though that can be done if you have your table structure in your code easily enough by looping over the list of columns and appending the alias.
$array = [
1=> "currency_id",
2=> "currency_name"
];
$columns = ""
foreach($array as $column){
$columns.= "company.".$column." AS company_".$column;
$columns.= ",client.".$column." AS client_".$column.",";
}
$columns = rtrim($columns,',');
Gives you
company.currency_id AS company_currency_id,client.currency_id AS client_currency_id,company.currency_name AS company_currency_name,client.currency_name AS client_currency_name
Add that after your SELECT pair.* and you get your columns from the currency table, aliased so you know which is which.
you can use the alias that you give to the tables:
SELECT client.currency_id as client_currency, company.currency_id as company_currency
FROM ex_pair
LEFT JOIN ex_currency as client ON client_curr = client.currency_id
LEFT JOIN ex_currency as company ON co_curr = company.currency_id

MySQL very simple join example requested with subtable

I keep falling back into questions with MySQL joining.
And I would like to request a very simple example I could use to continue my journey of understanding learning the MySQL syntax.
Let's say I got the following table's
test_testtable
testtable_id
testtable_name
testtable_user
testtable_option
testtable_textfield
test_testlink
testlink_id
testlink_link
testlink_address
test_address
address_id
address_name
address_phone
address_email
address_street
address_city
address_zip
I would like to make a selection like :
SELECT * (lets say I would define the fields) FROM `test_testable`
JOIN `test_testtable`.`testtable_id` = `test_testlink`.`testlink_link`
AND
JOIN `test_testlink`.`testlink_addres` = `test_address`.`address_id`
WHERE `user_id` = 5
Hence the linking structure is like:
test_testtable.testtable_id = leading
table test_testlink is a table to link the table test_testtable and test_address
And linking table test_testlink uses the field testlink_link to link to the table test_testtable, and uses the field testlink_address to link to the table test_address
This does not work. FOR ME.. Since I continuously seem to fail of catching the correct syntax logic.
So I hope that someone could give me a small example of how to correctly implement such a simple yet critical query!
TIAD!!
A general approach :
SELECT table1.* FROM table1
JOIN table2 ON table2.id_table1 = table1.id
JOIN table3 ON table3.id_table2 = table2.id
WHERE table1.id = 10
For your purpose :
SELECT * (lets say I would define the fields) FROM `test_testable`
JOIN `test_testlink` ON `test_testtable`.`testtable_id` = `test_testlink`.`testlink_link`
JOIN `test_address` ON `test_testlink`.`testlink_addres` = `test_address`.`address_id`
WHERE `user_id` = 5
Please read the reference
You are using wrong syntax. You should mention which tables to join first then based on which fields.
SELECT * (lets say I would define the fields) FROM `test_testable`
INNER JOIN test_testlink
ON `test_testtable`.`testtable_id` = `test_testlink`.`testlink_link`
INNER JOIN `test_address`
ON `test_testlink`.`testlink_addres` = `test_address`.`address_id`
AND `test_testtable`.`user_id` = 5
select * from testlink JOIN testtable ON testlink.tableid = testtable.ID
JOIN testaddress ON testlink.addressid = testaddress.ID
WHERE testtable.ID = 5

Getting data from 3 MySQL tables

I'm having a struggle here trying to grab some data from 3 database tables..
The idea is that users can fill out their profile with several fields, and I'm storing every profile field, field values and the users selected value in separate tables.
The structure of the tables look like this:
Table 'profile_fields'
- id
- name
- sort
- status (enum '0', '1')
Table 'profile_field_values'
- id
- profile_field_id
- name
Table 'user_profile_fields'
- user_id
- profile_field_id
- profile_field_value_id
Would be really nice if you could tell me how to construct this query, and why you used the JOIN you did.
Also, how would this table layout scale when the userbase grows?
Thank you so much in advance!
Edit:
OK, I still can't figure out how to make it return all the fields from 'profile_fields' along with the users selected option from 'user_profile_fields'. If the user hasn't selected a value, it should just be null.
This is my (non-functional) query so far:
SELECT PF.id AS field_id, PF.name AS field_name, UPF.profile_field_value_id AS value_id, PF.type, PFV.name
FROM profile_fields PF
LEFT JOIN profile_fields_values PFV ON PFV.profile_field_id = PF.id
LEFT JOIN user_profile_fields UPF ON UPF.user_id=1 AND PF.id = UPF.profile_field_id
WHERE length(PF.name) > 0 and PF.status = '1'
ORDER BY PF.sort
This query seems to work, but it does not fetch the name of the value from 'profile_field_values':
SELECT PF.id AS field_id, PF.name AS field_name, UPF.profile_field_value_id AS value_id, PF.type
FROM profile_fields PF
LEFT JOIN user_profile_fields UPF ON UPF.user_id =1
AND PF.id = UPF.profile_field_id
WHERE LENGTH( PF.name ) >0
AND PF.status = '1'
ORDER BY PF.sort
I think you have some unnecessary complexity in there. Maybe you should try
Table 'profile_fields'
id
name
sort
status (enum '0', '1')
Table 'profile_field_values'
id
user_id
profile_field_id
value
why are there 3 tables?
Seems like simple JOINs should work:
SELECT pf.id, pf.name, pf.sort, pf.status,
pfv.id, pfv.profile_field_id, pfv.name,
upf.user_id, upf.profile_field_id, upf.profile_field_value_id
FROM profile_fields pf
INNER JOIN profile_field_values pfv
ON pf.id = pfv.profile_field_id
INNER JOIN user_profile_fields upf
ON upf.profile_field_value_id = pfv.id AND upf.profile_field_id = pf.id
A Visual Explanation of SQL Joins
This uses an INNER JOIN to select all matching records from each table -- review the post to tell the difference between an INNER and an OUTER join.

SQL Advice - selecting multiple rows from a table as an innerJoin

I've been working on a project that until now has only needed to find 1 row from the joined table. But now I need to grab multiple rows..
So as it stand my sql works something like:
Select rows for each company for this particular project which alone would find company details (name, id, telephone.. blah).
Then I join a table that contains form data submitted for each company (multiple forms - so multiple records)
Until now i have been specifying one formid to look for in the join, but now i need to specify multiple ones.
If I use WHERE form_id = 1 OR form_id = 2 OR form_id = 3 ... I get a result of only the first form match that is found per company..
If I mix up the query so it looks for the forms 1st and returns multiple records for each company with different form data - that works in this sense..
But I am then looping through this array in a view and creating a table row per record (previously each row was a new company) but using the latter would cause multiple records to show for the same company.
Any way I can do this? I tried group by with the latter method but this results in only 1 record again.
SELECT DISTINCT p.project_company_has_user_id, p.project_company_has_user_project_id, p.project_company_has_user_user_id, c.company_id, c.company_hall_no, c.company_company_name, c.company_type, c.company_country, c.company_stand_number, c.company_image_file_1, p2.project_id, p2.project_name, u.user_id, u.user_username, o.orders_id, o2.order_detail_id, o2.order_detail_product_id, f2.form_question_has_answer_id, f2.form_question_has_answer_request, f2.form_question_has_answer_form_id, f2.form_question_has_answer_user_id
FROM project_company_has_user p
INNER JOIN company c ON p.project_company_has_user_company_id = c.company_id
INNER JOIN project p2 ON p.project_company_has_user_project_id = p2.project_id
INNER JOIN user u ON p.project_company_has_user_user_id = u.user_id
INNER JOIN form f ON p.project_company_has_user_project_id = f.form_project_id
LEFT JOIN orders o ON p.project_company_has_user_user_id = o.orders_user_id
LEFT JOIN order_detail o2 ON ((o2.order_detail_orders_id = o.orders_id AND (o2.order_detail_product_id = 65 OR o2.order_detail_product_id = 68 OR o2.order_detail_product_id = 64)))
LEFT JOIN form_question_has_answer f2 ON ((f2.form_question_has_answer_form_id = 297 AND f2.form_question_has_answer_user_id = p.project_company_has_user_user_id))
WHERE (f.form_template_name = "custom" AND p.project_company_has_user_garbage_collection = 0 AND p.project_company_has_user_project_id = 48) AND (LCASE(c.company_country) LIKE "%uk%" OR LCASE(c.company_country) LIKE "%uk%") ORDER BY company_company_name asc
you need another field in order_detail as o2 . this field is row_index(position),etc for positioning record
LEFT JOIN order_detail o2 ON (o2.row_index=1 AND (o2.order_detail_orders_id = o.orders_id AND (o2.order_detail_product_id = 65 OR o2.order_detail_product_id = 68 OR o2.order_detail_product_id = 64)))
Personally I would use an Outer Join for the table of which elements you need to list all matches. Should you them need to clean up that data you can build the logic into the Join Condition (as step 2). Depending on the volume of data you are handling and whether or not you need to reuse it later in the same proc, you may want to post that primary dataset into a temp table and use that as source (primary) for your later logic.
Hope that helps. If you need the code, let me know, but it is pretty straight forward.
Regards
Mac

Categories