MySQL create Tables/Views - mysql

I don't know if the title is correct but here goes my problem.
So, I want to create View in phpmyadmin using data from several tables (picture below), View that represents maintenance for lamps with fields from several tables (substation, post_type, area, lamp_type, failure and maintenance)
Here are tables with connections:
I've manage somehow and created something like this(picture below), which I managed to create using this block of code:
CREATE OR REPLACE VIEW
v_lamp_I
AS
SELECT
lamps.id,
substation.code AS sub_code,
substation.name AS sub_name,
lamps.lamp_code,
post_type.descript AS post_ty,
lamp_type.descript AS lamp_ty,
area.descript AS area_name,
rasvjeta.adress,
DATE_FORMAT(date_maintenance, "%d.%m.%Y.") AS date_main,
lamps.geo_long,
lamps.geo_lat
FROM lamps
INNER JOIN substiation ON substiation.id = lamps.substiation_id
INNER JOIN post_type ON post_type.id = lamps.post_type_id
INNER JOIN lamp_type ON lamp_type.id = lamps.lamp_type_id
INNER JOIN area ON area.id = rasvjeta.area_id
INNER JOIN maintenance ON maintenance.lamps_id = lamps.id
I've managed to create view but the problem is with that view I can see only rows/lamps(sifra_lampe) which were maintained, only 4. In table lamps
I've 24 entries in and only 4 entries for maintenance.But, I want to see all 24 entries and if there was no maintenance for that particular lamp, field can be empty with date format (00-00-00 or it can be NULL) and for entries/lamps that were maintained I want to be visible date field.
Here is table lamps with entries.
And here is view with maintenance date. As you can see there are only 6 entries
I want to see the rest of the entries, for lamps that were not maintained entries can be null or date format like this (00-00-00) and for lamps that were maintained date format can stay the same, in short I want to see all entries not only those which were maintained. Thank you and sorry for long question. I didn't know how to construct meaningful and short question so wrote everything.

create or replace view
v_lamp_I as
SELECT lamps.id,
substation.code AS sub_code,
substation.name AS sub_name,
lamps.lamp_code,
post_type.descript AS post_ty,
lamp_type.descript AS lamp_ty,
area.descript AS area_name,
rasvjeta.adress,
lamps.geo_long,
lamps.geo_lat
FROM lamps
INNER JOIN substiation ON substiation.id = lamps.substiation_id
INNER JOIN post_type ON post_type.id = lamps.post_type_id
INNER JOIN lamp_type ON lamp_type.id = lamps.lamp_type_id
INNER JOIN area ON area.id = rasvjeta.area_id;
CREATE OR REPLACE VIEW
v_lamp_new
AS
select v_lamp_I.*,DATE_FORMAT(date_maintenance, "%d.%m.%Y.") AS date_main
from v_lamp_I
LEFT JOIN maintenance ON v_lamp_I.id = maintenance.lamps_id;

CREATE OR REPLACE VIEW
v_lamp_I
AS
select tbl_lamp.*,DATE_FORMAT(date_maintenance, "%d.%m.%Y.") AS date_main
from (SELECT lamps.id,
substation.code AS sub_code,
substation.name AS sub_name,
lamps.lamp_code,
post_type.descript AS post_ty,
lamp_type.descript AS lamp_ty,
area.descript AS area_name,
rasvjeta.adress,
lamps.geo_long,
lamps.geo_lat
FROM lamps
INNER JOIN substiation ON substiation.id = lamps.substiation_id
INNER JOIN post_type ON post_type.id = lamps.post_type_id
INNER JOIN lamp_type ON lamp_type.id = lamps.lamp_type_id
INNER JOIN area ON area.id = rasvjeta.area_id) as tbl_lamp
LEFT JOIN maintenance ON tbl_lamp.id = maintenance.lamps_id

Related

Using an alias to form an inner join

I have a problem which I cant figure out, and have looked on google and similar questions on here, but they are just not quite the same.
I am trying to build a MySQL Query which has two parts, the first is easy and i have done this fine, as it uses existing relationships, see...
SELECT
clientsites.SiteName,
clients.ClientName,
pafaddresses.PostTown,
pafaddresses.PostCode,
CONCAT("XXXXXXX", Replace(UPPER(pafaddresses.PostCode),' ','')) AS JouneyKeytemp,
clientsites.SiteType
FROM clientsites
INNER JOIN clients ON clientsites.ClientFk = clients.ClientPk
INNER JOIN pafaddresses ON clients.ActualPAF = pafaddresses.id
You will see from this code that an alias is generated which concats two postcodes and looks like xxxxxxxyyyyyy, this does work but for obvious reasons ive removed the actual postcodes.
What I now what to do is to bring in two fields from an unrelated table called Journeys:
SELECT
JourneyKey,
SingleDistance,
SingleTime
FROM journeys
I want to bring in SingleDistance and SingleTime, where the Journey Key = Generated Alias of JourneyKeyTemp.
I have tried adding the following:
INNER JOIN journeys ON JouneyKeytemp = journeys.JourneyKey
But I just keep getting a syntax error.
Any help would be appreciated.
Repeat the expression in join predicate:
INNER JOIN journeys
ON CONCAT("XXXXXXX", Replace(UPPER(pafaddresses.PostCode),' ','')) = journeys.JourneyKey
Or you can create a subquery:
select * from(
SELECT
clientsites.SiteName,
clients.ClientName,
pafaddresses.PostTown,
pafaddresses.PostCode,
CONCAT("XXXXXXX", Replace(UPPER(pafaddresses.PostCode),' ','')) AS JouneyKeytemp,
clientsites.SiteType
FROM clientsites
INNER JOIN clients ON clientsites.ClientFk = clients.ClientPk
INNER JOIN pafaddresses ON clients.ActualPAF = pafaddresses.id)t
INNER JOIN journeys ON t.JouneyKeytemp = journeys.JourneyKey

Why can't I exclude this row based on a condition?

http://sqlfiddle.com/#!3/3ec1f/119
Here's my fiddle...I want the result to look like this but the query I'm using doesn't do that:
My problem with the query is that I can't seem to exclude "The Kingdom of the Crystal Skull" using the exclusion_flag condition. I also don't know why it seems that Contract 3 (Raiders of the Lost Arc) is not showing up either. I have been toiling with this for hours and have no idea what the problem is. I tried looking into subqueries, but I'm not sure that's the solution...
There's a couple of questions/issues there so I'll try to address them individually.
1) You can't exclude "The Kingdom of the Crystal Skull" using the exclusion_flag because contract_sid 7 and 8 both refer to product_list_sid 3 which includes "The Kingdom of the Crystal Skull" - you would need to create a separate product_list_sid if you wanted a contract which excluded it.
2) "Raiders of the Lost Arc" (contract_sid 3) isn't showing up because it's a "single product" contract, and your query only joins from scope to product_list_join using product_list_id - contract_sid 3 is in the product_sid column so you need a separate join to cater for contracts that use product_sid instead of product_list_sid (I assume that a contract can't use both). This is a pretty dodgy schema design but here's a query that solves that issue. Notice the use of LEFT OUTER JOIN to indicate that the table being joined to might not contain any rows (for example when scope.product_list_sid is NULL but scope.product_sid is not).
SELECT s.contract_sid,
c.contract_description,
ISNULL(p.product_description, p2.product_description) AS product_description
FROM scope s
JOIN contracts c ON (c.contract_sid = s.contract_sid)
LEFT OUTER JOIN
product_list_join plj ON (plj.product_list_sid = s.product_list_sid)
LEFT OUTER JOIN
products p ON (p.product_sid = plj.product_sid)
LEFT OUTER JOIN
products p2 ON (p2.product_sid = s.product_sid)
WHERE s.exclusion_flag = 'N'
ORDER BY s.contract_sid;
Here's the SQLFiddle for my solution: http://sqlfiddle.com/#!3/fc62e/10
Edit: After posting this I realised what you're actually trying to do - the scope table not only provides the details of contracts but also provides specific products to exclude from contracts. Again, this is bad schema design and there should be a separate scope_exclusions table or something, but here's a query that does that and excludes "The Kingdom of the Crystal Skull" as requested:
SELECT inner_query.contract_description,
inner_query.product_description
FROM (
SELECT s.contract_sid,
c.contract_description,
ISNULL(p.product_sid, p2.product_sid) AS product_sid,
ISNULL(p.product_description, p2.product_description) AS product_description
FROM scope s
JOIN contracts c ON (c.contract_sid = s.contract_sid)
LEFT OUTER JOIN
product_list_join plj ON (plj.product_list_sid = s.product_list_sid)
LEFT OUTER JOIN
products p ON (p.product_sid = plj.product_sid)
LEFT OUTER JOIN
products p2 ON (p2.product_sid = s.product_sid)
WHERE s.exclusion_flag = 'N'
) inner_query
WHERE NOT EXISTS ( SELECT 1
FROM scope
WHERE exclusion_flag = 'Y'
AND contract_sid = inner_query.contract_sid
AND product_sid = inner_query.product_sid )
ORDER BY inner_query.contract_description;
SQL Fiddle: http://sqlfiddle.com/#!3/fc62e/14

Taking one column from MySQL joined tables

I have a query in MySQL and I am making a crystal report by using this.
Now inside the query i have a column called scan_mode and it is coming from gfi_transaction table. This scan_mode I am using in report to suppress some sections. But some times this value is coming null for some transaction ids.
So now I want to take this scan_mode as separate query so that it will work.
Can any one please help how I can modify the below query to take only scan_mode column.
SELECT
cc.cost_center_code AS cccde,
cc.name AS ccnme,gf.scan_mode,
cc.cost_center_id AS ccid,
site.name AS siteme,
crncy.currency_locale AS currency_locale,
cntry.language AS LANGUAGE,
cntry.country_name AS cntrynm,
crncy.decimal_digits AS rnd,
gf.transaction_no AS Serial_No,
brnd.name AS brand_name,
rsn.description AS reason,
gf.comment AS COMMENT,
ts.status_description AS STATUS,
DATE_FORMAT(gf.created_date,'%d/%m/%Y') AS created_date,
gf.created_by AS created_by,
IFNULL(gf.approval_no,'Not authorized') AS Trans_no,
gf.approved_date AS approval_dt,
gf.approved_by AS approved_by,gf.status AS status1,
IFNULL(loc.cost_center_code,cc.cost_center_code) AS cur_location,
gf.document_ref_no,gf.document_ref_type,
,DATE_FORMAT(document_ref_date1,'%d/%m/%Y')) AS invoice_no
FROM
gfi_transaction gf
INNER JOIN gfi_instruction gfn ON (gf.transaction_id=gfn.transaction_id)
INNER JOIN gfi_document_instruction doc ON (gf.ref_transaction_no = doc.document_instruction_id)
INNER JOIN reason rsn ON (gf.reason_id = rsn.reason_id)
INNER JOIN gfi_status ts ON (gf.status = ts.gfi_status_id)
INNER JOIN transaction_type tt ON (gf.transaction_type_id = tt.transaction_type_id)
INNER JOIN brand brnd ON(gf.brand_id=brnd.brand_id)
-- cc details
INNER JOIN cost_center cc ON (brnd.parent_brand = cc.brand_id OR gf.brand_id = cc.brand_id)
INNER JOIN site site ON(cc.site_id = site.site_id)
INNER JOIN country cntry ON (site.country_id = cntry.country_id)
INNER JOIN currency crncy ON (cntry.currency_id=crncy.currency_id)
LEFT OUTER JOIN alshaya_location_details loc ON
(gf.brand_id = loc.brand_id AND loc.cost_center_id = gf.cost_centre_id)
LEFT OUTER JOIN alshaya_location_details locto ON
(locto.cost_center_id = gf.from_cost_center_id)
WHERE
gf.transaction_id='{?TransID}'
AND rsn.transaction_type_id IN (10,11,14)
wow, that's a big query. I ran across a similar problem in a query i was building and found the if syntax to be a solution to my problem. This was also answered in this question: MYSQL SELECT WITHIN IF Statement
$psdb->query = "SELECT count, s.classid,
if (k.sic != k.siccode, k.siccode, s.siccode) as siccode,
if (k.sic != k.siccode, k.sicdesc, s.sicdesc) as sicdesc,
if (k.sic != k.siccode, k.sicslug, s.sicslug) as sicslug
FROM ...
It looks like scan_mode column comes from "gfi_transaction" table which seems to be primary table in your query. If you get null for this column then it means your table itself have NULL value for this column. Taking that separately in a query wont solve your problem. Try replacing null with a default value and handle it in code. You can add default value instead of NULL by using ifnull(scan_mode, 'default')

How to use right join correctly

Table Locations
loc_id loc_name hier2 hier3 hier4 hier5 hier6 hier7 hier8 hier9
152675 Castelli 105 109 0 319 14356 152673 152675 0
14356 Rome 105 109 0 319 14356 0 0 0
...
Table Lacations References
oid name loc_id
12 Demo Villa 152675
...
Now i try to find some entries a user searches by entering the string "caste":
SELECT geo.loc_id, geo.loc_name AS name
FROM locations AS geo
LEFT JOIN locations AS geoh3 ON geo.hier3 = geoh3.loc_id
LEFT JOIN locations AS geoh4 ON geo.hier4 = geoh4.loc_id
LEFT JOIN locations AS geoh8 ON geo.hier8 = geoh8.loc_id
WHERE geo.loc_name LIKE 'caste%'
GROUP BY geo.loc_name
This works. I get the entry with loc_id 152675
Now i only want to get those entrys we have objects in. So i join the reference table:
SELECT geo.loc_id, geo.loc_name AS name
FROM locations AS geo
LEFT JOIN locations AS geoh3 ON geo.hier3 = geoh3.loc_id
LEFT JOIN locations AS geoh4 ON geo.hier4 = geoh4.loc_id
LEFT JOIN locations AS geoh8 ON geo.hier8 = geoh8.loc_id
RIGHT JOIN locations_xref AS gx ON geo.loc_id = gx.loc_id
WHERE geo.loc_name LIKE 'caste%'
GROUP BY geo.loc_name
This works. Again i get the location entry with loc_id 152675 because theres a reference.
PROBLEM
Now the user searches for "rome". I dont get any entry because there is no object reference directly to the city "Rome". The existing object is referenced to a district of rome.
As you can see the district and the city entries have hierarchy IDs which can be used to identify the correct structure. I just cant get it to work together with the reference table, so i only get those objects which are in "rome" or in a district, which is part of rome.
Any help is greatly appreciated!
I don't know much about your data but from first sight it seems that hier6 has the information about relationship between Rome and Castelli. So the query you need may look something more or less like this:
SELECT geo.loc_id, geo.loc_name AS name
FROM locations AS geo
LEFT JOIN locations AS geoh3 ON geo.hier3 = geoh3.loc_id
LEFT JOIN locations AS geoh6 ON geo.hier6 = geoh6.loc_id
LEFT JOIN locations AS geoh4 ON geo.hier4 = geoh4.loc_id
LEFT JOIN locations AS geoh8 ON geo.hier8 = geoh8.loc_id
RIGHT JOIN locations_xref AS gx ON geo.loc_id = gx.loc_id
WHERE geoh6.loc_name LIKE 'rome%'
GROUP BY geo.loc_name
You can tweak your query (as Karolis suggested), but I don't think that will give you what you want. Your query will return 'Castelli' when you search for 'Rome%', but it won't return 'Rome'. It won't return 'Rome', because 'Rome' isn't in your xref table.
To return 'Rome' with this kind of query, you'll need to insert a row for 'Rome' into the xref table.
You can get all the things that are "in" Rome with a UNION, but it doesn't reference your xref table at all.
select la.loc_id, la.loc_name
from locations la
where la.loc_name like 'Rome%'
union
select lb.loc_id, lb.loc_name
from locations lb
inner join locations lc on lc.hier6 = lb.hier6
It's not clear to me how you determine which column to use for the join at run time.
Later . . .
If you don't know which columns to use at run time, you have to LEFT JOIN on all of them. And since you don't know whether the search string might refer to a value joined through column hier2, hier3, hier4, etc., then you have to check each of those columns for a match, too.
If locations_xref acts like a filter, then you need an inner join on that table, along with a row for 'Rome'. (Because you have properties in Rome.) Probably something along these lines.
SELECT geo.loc_id, geo.loc_name AS name
FROM locations AS geo
LEFT JOIN locations AS geoh2 ON geo.hier2 = geoh2.loc_id
LEFT JOIN locations AS geoh3 ON geo.hier3 = geoh3.loc_id
LEFT JOIN locations AS geoh4 ON geo.hier4 = geoh4.loc_id
LEFT JOIN locations AS geoh5 ON geo.hier5 = geoh5.loc_id
LEFT JOIN locations AS geoh6 ON geo.hier6 = geoh6.loc_id
LEFT JOIN locations AS geoh7 ON geo.hier7 = geoh7.loc_id
LEFT JOIN locations AS geoh8 ON geo.hier8 = geoh8.loc_id
LEFT JOIN locations AS geoh9 ON geo.hier9 = geoh9.loc_id
INNER JOIN locations_xref lx on lx.loc_id = geo.loc_id
WHERE geo.loc_name LIKE 'Rom%'
or geoh2.loc_name like 'Rom%'
or geoh3.loc_name like 'Rom%'
or geoh4.loc_name like 'Rom%'
or geoh5.loc_name like 'Rom%'
or geoh6.loc_name like 'Rom%'
or geoh7.loc_name like 'Rom%'
or geoh8.loc_name like 'Rom%'
or geoh9.loc_name like 'Rom%'
Before you get too invested in this model, you should take a look at Bill Karwin's database antipatterns. "Naive Trees" starts on slide 48.

Error with my left joins?

I'm thinking the coffee isn't strong enough today. I need to query the table fb-celebotd to get the photoid that matches the fb-celebotd.celebdate. Most of the other info needed is dependent on the photos table.
The following is giving me a mysql error:
Select photos.*,photographer.name, events.eventname, events.eventhome, subevents.subeventname, photodir.photodir, fb-celebotd.celebdate, fb-celebotd.trivia
from photos
LEFT JOIN fb-celebotd ON (photos.photoid = fb-celebotd.photoid)
LEFT JOIN photodir ON (photos.photodirid = photodir.photodirid)
LEFT JOIN photographer ON (photos.photographerid = photographer.photographerid)
LEFT JOIN events ON (photos.eventid = events.eventid)
LEFT JOIN subevents ON (photos.subeventid = subevents.subeventid)
WHERE fb-celebotd.celebdate=1277092800
Is this doable in one query or do I have to query fb-celebotd for the photoid and trivia first and then query other tables based on the photoid?
Thanks.
Should fb-celebotd (with a dash) be fb_celebotd (with an underscore)? If the table name has a dash, then you'll have to quote the table name: "fb-celebotd". Otherwise the dash is treated as a minus sign and tries to subtract celebotd from fb (both unknown).
If you really have a table named fb-celebotd, then you need to quote the table name every time you use it in a query:
Select photos.*,photographer.name, events.eventname, events.eventhome, subevents.subeventname, photodir.photodir, `fb-celebotd`.celebdate, `fb-celebotd`.trivia
from photos
LEFT JOIN `fb-celebotd` ON (photos.photoid = `fb-celebotd`.photoid)
LEFT JOIN photodir ON (photos.photodirid = photodir.photodirid)
LEFT JOIN photographer ON (photos.photographerid = photographer.photographerid)
LEFT JOIN events ON (photos.eventid = events.eventid)
LEFT JOIN subevents ON (photos.subeventid = subevents.subeventid)
WHERE `fb-celebotd`.celebdate=1277092800