I want to know if I can hardcode a value within my select statement. I have the following mysql query that I use to generate a list.
I use concat to build this string as part of creating the list.
However, now I need to generate an 'Unknown' record as part of the list.
For example:
20(ABC Object #20)
24(DEF Object #24)
I want to add a value of 'UKNOWN' to the top of the list:
--(UNKNOWN -- )
20(ABC Object #20)
24(DEF Object #24)
Here is what I have so far:
SELECT CAST(p.Serial AS UNSIGNED INTEGER) as Serial,
p.Object_ID,
p.Part_ID,
st.Description AS ObjectDesc,
s.Object_Num,
concat(Serial,' (',st.Desc,' #',s.Object_Num,')') as DropList
FROM Parts p LEFT JOIN Objects s ON p.Object_ID = s.Object_ID
LEFT JOIN ObjectTypes st ON s.ObjectType_ID = st.ObjectType_ID
Can I hardcode that string in my select statement? If so, how do I do that?
If I understand correctly, you want a new row. You can use UNION
SELECT "" as Serial,
"" as Object_ID,
"" as ObjectDEsc,
"" as Object_Num,
"--(UNKNOWN -- )" as DropList
UNION
SELECT CAST(p.Serial AS UNSIGNED INTEGER) as Serial,
p.Object_ID,
p.Part_ID,
st.Description AS ObjectDesc,
s.Object_Num,
concat(Serial,' (',st.Desc,' #',s.Object_Num,')') as DropList
FROM Parts p LEFT JOIN Objects s ON p.Object_ID = s.Object_ID
LEFT JOIN ObjectTypes st ON s.ObjectType_ID = st.ObjectType_ID
In a union query each part must select the same columns. Since your original query included Serial, Object_ID, Part_ID and ObjectDesc, the first part must include it as well.
Related
I have a table of employees with names and two surnames (in Spain two surnames are required).
To avoid erroneous entries, I have ONE surname table called "ST_JLE_Apellidos". In this way, what I store is the surname number, not the surname itself.
To feed the form I use the following SQL string (Where Table "Apellido2" is an instance of Table "Apellido1":
SELECT
JLE_Personal.Id_Personal_Personal,
JLE_Personal.Personal_NIF,
Apellido1.Personal_Apellido,
Apellido2.Personal_Apellido,
ST_JLE_Personal_Nombres.Personal_Nombre,
ST_JLE_CargosEnLaEmpresa.CargosEnLaEmpresa_CargoEnLaEmpresa,
ST_JLE_Municipios.Municipios_Municipio,
ST_JLE_Provincias.Provincias_Provincia,
ST_JLE_Paises.Paises_NombreCast,
JLE_Personal.Personal_Alta_FechaInicial,
JLE_Personal.Personal_Alta_FechaFinal
FROM
ST_JLE_Personal_Apellidos AS Apellido2
INNER JOIN (
ST_JLE_Personal_Apellidos AS Apellido1
INNER JOIN (
(
ST_JLE_Paises
INNER JOIN ST_JLE_Provincias ON ST_JLE_Paises.Id_Paises_Pais = ST_JLE_Provincias.Cod_Provincias_Pais
)
INNER JOIN (
ST_JLE_Municipios
INNER JOIN (
ST_JLE_CargosEnLaEmpresa
INNER JOIN (
ST_JLE_Personal_Nombres
INNER JOIN JLE_Personal ON ST_JLE_Personal_Nombres.Id_Personal_Nombre = JLE_Personal.Cod_Personal_Nombre
) ON ST_JLE_CargosEnLaEmpresa.Id_CargosEnLaEmpresa_CargoEnLaEmpresa = JLE_Personal.Cod_Personal_Cargo
) ON ST_JLE_Municipios.Id_Municipios_Municipio = JLE_Personal.Cod_Personal_Municipio
) ON ST_JLE_Provincias.Id_Provincias_Provincia = ST_JLE_Municipios.Cod_Municipios_Provincia
) ON Apellido1.Id_Personal_Apellido = JLE_Personal.Cod_Personal_Apellido1
) ON Apellido2.Id_Personal_Apellido = JLE_Personal.Cod_Personal_Apellido2;
Here is the MS-Access graphic window of the query:
And here is the result:
Everything correct so far.
The problem comes when I try to use a continuous form that contains the two last names:
TextBox 1: Apellido1.Personal_Apellido
TextBox 2: Apellido2.Personal_Apellido
MS-Access accepts both text boxes, but when I run the form, then Text Box 2 automatically changes to Apellido1.Personal_Apellido:
What could be the mistake that I am making?
Thanks in advance
I have the following code:
SELECT stores_tb.stores, sum(products_tb_tb.prices)
from products_tb
inner join stores_tb
on products_tb.id_store = stores_tb.id_store
where products_tb.barcode IN ($barcodes)
group by stores_tb.stores
order by sum(products_tb.prices)
Being the $barcodes an array (already converted to a string) that I receive via ajax in a php file that executes the MySQL.
The thing is that the IN is inclusive, using OR for each of the array values, meaning that if one of the stores required on the SELECT have one, but not all of the barcodes in the array, it will be shown.
I wanna know if there is a function like the IN (or a way to use the IN function) in which it will return only the stores that have all of the barcodes passed in the array, the equvilant of using AND instead of OR for each of the array values.
You can do this with a having clause:
select s.stores, sum(p.prices)
from products_tb p join
stores_tb s
on p.id_store = s.id_store
where p.barcode IN ($barcodes)
group by s.stores
having count(distinct p.barcode) = $n -- the number of codes that need to match
order by sum(p.prices);
The $n value is the length of the $barcodes list (strictly speaking, the number of unique items in it).
Instead of an array and an IN clause You could use a subselect and the ALL operator
SELECT stores_tb.stores, sum(products_tb_tb.prices)
from products_tb
inner join stores_tb
on products_tb.id_store = stores_tb.id_store
where products_tb.barcode = ALL (
select barcode from my_table )
)
group by stores_tb.stores
order by sum(products_tb.prices)
https://dev.mysql.com/doc/refman/5.7/en/any-in-some-subqueries.html
https://dev.mysql.com/doc/refman/5.7/en/all-subqueries.html
i am trying to make a view in MS SQL having join of two table and an individual field.
i have done the joining part but now i want to add a new field in this view which is not in any of the table which is joined.
so anybody have any idea how i can create this new field in the view.
In case you want a default value for all your rows in the ACTIVE field, try this
CREATE VIEW Slots AS
SELECT Event.EventId,
Event.eventName,
examCenter.centerId,
examCenter.centerName,
slotTime.slotTimeId,
slotTime.FromTime,
slotTime.ToTime,
slotTime.Dated,
examCenter.noOfSeats,
CAST(1 AS bit) AS Active
FROM examCenter
INNER JOIN Event
ON examCenter.eventId = Event.EventId
INNER JOIN slotTime ON Event.EventId = slotTime.eventId
If the value for the ACTIVE field depends on some condition, say
slottime.Dated => getdate()
then, you will need to replace
CAST(1 AS bit) AS Active
in the above code, with
CAST(CASE WHEN slottime.Dated => getdate() THEN 1 ELSE 0 AS bit) AS ACTIVE
You can explicitly name each field if you need, aliasing them with AS as required. For example:
SELECT si.field1 as si_field1,
si.field2 as si_field2,
ind_data.field1 as ind_data_field1
FROM sites_indexed as si
LEFT JOIN individual_data as ind_data
ON si.id = ind_data.site_id
And then you can reference the aliased names in your result set.
I have a table activity_types which contains the text for activities e.g.
New project has been assigned to {user} with name {project}
New discussion has been posted by {client} on {project}
Project {project} has been closed by {user}
A draft has been approved by {client} on {project}
and so on
I have another table in which the id of these texts has been populated.
Now my requirement is to fetch these by replacing the text within {} with their actual values like {client} should be replaced with client name, {project} should be replaced with project name.
I have tried using nested replace mysql function but it returns null string. Here is my query
SELECT REPLACE(REPLACE(REPLACE(att.type_text, '{project}', p.project_business_name), '{user}', u.user_fullname), '{client}', c.client_name) AS activity, a.*
FROM activities a
LEFT JOIN activity_types AS att ON att.type_id = a.activity_type
LEFT JOIN users u ON u.user_id = a.activity_user AND a.activity_user IS NOT NULL
LEFT JOIN projects p ON p.project_id = a.activity_project AND p.project_is_removed = '0'
LEFT JOIN clients c ON c.client_id = a.activity_client AND a.activity_client IS NOT NULL;
The problem is that if i replace the c.client_name with static text it works fine but when i replace the static string with c.client_name it return null in activities which does not have {client}. Any guesses where am i doing wrong?
try adding COALESCE on the column
...,COALESCE(c.client_name, ''),
basically if the column (c.client_name) is null, it will be replace with empty string.
what happens is that when part of the string is replace with null, the whole string becomes null.
SQL null is contagious. Once you get a null value somewhere and use that null value in functions and derived values, the whole result becomes null. As such, if any of your fields in the REPLACE() chain are null, the whole result becomes null. You can try something like
COALESCE(name_of_field, '')
or
IFNULL(name_of_field, '')
to convert those nulls into an empty string.
I use data from http://geonames.org. The table structure is as follows:
GN_Name 1 - 0:N GN_AlternateName
They are linked on:
(PK)GN_Name.GeoNameId == (FK)GN_AlternateName.GeoNameId
GN_Name is the main table containing all place names.
GN_AlternateName contains names in other languages if any.
EX:
GN_Name.Name - Stockholm
GN_AlternateName.AlternateName - Estocolmo (if IsoLanguage=="es")
Rules:
I want to use GN_AlternateName.AlternateName if it exists for the specified language and if it starts with the search string.
If not, i want to use GN_Name.Name if it starts with the search string.
I want GeoNameId to be unique.
Basically I could outer join in first record only, but that seemed to decrease performance.
I've got the following SQL (basically modified SQL from a LINQ query). The problem is that it only finds 'Estocolmo' if search string starts with "stock". "estoc" yields nothing.
select
distinct(n.GeoNameId) as Id,
an.IsoLanguage,
CASE WHEN (an.AlternateName like N'estoc%')
THEN an.AlternateName
ELSE n.Name
END AS [The name we are going to use]
from GN_Name as n
LEFT OUTER JOIN GN_AlternateName as an
ON n.GeoNameId = an.GeoNameId
AND 'es' = an.IsoLanguage
WHERE n.Name like N'estoc%'
UPDATE
Thanks Rahul and Lee D.
I now have the following:
select
distinct(n.GeoNameId) as Id,
an.IsoLanguage,
CASE WHEN (an.AlternateName like N'estoc%')
THEN an.AlternateName
ELSE n.Name
END AS [The final name]
from GN_Name as n
LEFT OUTER JOIN GN_AlternateName as an
ON n.GeoNameId = an.GeoNameId
AND 'es' = an.IsoLanguage
WHERE (n.Name LIKE N'estoc%' OR an.AlternateName LIKE N'estoc%')
This performs LIKE twice on an.AlternateName. Is there any way i could get rid of on LIKE clause?
UPDATE 2
Andriy M made a nice alternative query using COALESCE. I changed it a little bit and ended up with the following:
SELECT Id, LocalisedName
FROM (
SELECT
n.GeoNameId AS Id,
an.IsoLanguage,
COALESCE(an.AlternateName, n.Name) AS LocalisedName
FROM n
LEFT JOIN GN_AlternateName AS an ON n.GeoNameId = an.GeoNameId
AND IsoLanguage = 'es'
) x
WHERE LocalisedName LIKE 'estoc%'
This query does exactly what i am looking for. Thanks!
Here's a probable solution of the problem, which uses a slightly different apporach:
SELECT Id, LocalisedName
FROM (
SELECT
n.GeoNameId AS Id,
an.IsoLanguage,
COALESCE(an.AlternateName, n.Name) AS LocalisedName
FROM GN_Name AS n
LEFT JOIN GN_AlternateName AS an ON n.GeoNameId = an.GeoNameId
AND IsoLanguage = 'es'
) x
WHERE LocalisedName LIKE 'estoc%'
(Changed it based on your update.)
If I understand correctly, in your example the value 'Estocolmo' is in the GN_AlternateName.AlternateName column, so would be filtered out by the where clause which only looks at GN_Name.Name. What if you change the last line of SQL to:
WHERE n.Name LIKE N'estoc%' OR an.AlternateName LIKE N'estoc%'
I'm assuming 'estoc%' is your search string.
I guess you need to modify the WHERE clause to check in GN_AlternateName table as well
WHERE n.Name like N'estoc%' OR an.AlternateName like 'N'estoc%'