Related
Informix 12.10
tblItems
(
Type SMALLINT, {Precious Metal = 1, Other = 2}
Description VARCHAR,
Quantity SMALLINT,
Name VARCHAR,
Weight DECIMAL(5,1),
Purity SMALLINT,
Brand VARCHAR,
Model VARCHAR,
SerialNum VARCHAR
);
EDIT UPDATE: Sample data below is stored in tblItems.Type and tblItems.Description. Please note that the contents in Description column are all uppercase characters and may also include punctuation character.
2|1LAPTOP APPLE 15.5" MODEL MACKBOOK PRO,S/N W80461WCAGX, WITH CHARGER||||||||
1|1RING 2.3PW 14K||||||||
2|DRILL RIOBY, MODEL D5521 S/N77720||||||||
2|TRIMMER TORO, MODEL 0242 S/N 66759||||||||
2|CELL SAMSUNG NOTE3, MODEL SM-N900T S/N RV8F90YLZ9W||||||||
I need to parse the sample item descriptions into the columns below, using the rules mentioned in the comments :
Quantity, {if description string does not start with a number, then Quantity = 1}
Name, {Always the first element if description has no quantity, second element if quantity present]
Weight, {Always before "PW" if Type = 1, Default to zero if Type = 2}
Purity, {Always before "K" if Type = 1, Default to NULL if Type = 2}
Brand, {Always the second element in description, if present}
Model, {Always after "MODEL", with or without a space}
Serial Number {Always after "S/N", with or without a space}
I would like to do this with an UPDATE statement, but if Informix has an import utility tool like SQL-Server's SSIS, then that could be a better option.
UPDATE, Expected Results:
Quantity 1 1 1 1 1
Name LAPTOP RING DRILL TRIMMER CELL
Weight 0.0 2.3 0.0 0.0 0.0
Purity 14
Brand APPLE RIOBY TORO SAMSUNG
Model MACKBOOK PRO D5521 0242 SM-N900T
SerialNum W8046WCAGX 77720 66759 RV8F90YLZ9W
Assuming you are using Informix 12.10.XC8 or above, you can try using regular expressions to parse the description string (see the online documentation here).
For the serial number, for example, you can do:
UPDATE tblitems
SET
serialnum =
DECODE
(
regex_match(description, '(.*)(S\/N)(.*)', 3)
, 't'::BOOLEAN, regex_replace(description, '(.*)(S\/N)([[:blank:]]?)([[:alnum:]]*)(.*)', '\4', 0, 3)
, 'f'::BOOLEAN, ''
)
So in the previous example I am testing if the description contains the S/N string and if that is true I use regex_replace to return the value after it, in this case the 4th matching group in the regular expression (I am not using regex_extract to get the value because it seems to return multiple values and I get error -686).
You can extend this approach to the rest of the columns and see if regular expressions are enough to parse the description column.
If you're looking for a SQL Server option and open to a Split/Parse function which maintains the sequence
Example
Select A.Type
,A.Description
,C.*
From YourTable A
Cross Apply (values ( replace(
replace(
replace(
replace(A.Description,',',' ')
,' ',' ')
,'Model ','Model')
,'S/N ','S/N')
)
)B(CleanString)
Cross Apply (
Select Quantity = IsNull(left(max(case when RetSeq=1 then RetVal end),NullIf(patindex('%[^0-9]%',max(case when RetSeq=1 then RetVal end)) -1,0)),1)
,Name = substring(max(case when RetSeq=1 then RetVal end),patindex('%[^0-9]%',max(case when RetSeq=1 then RetVal end)),charindex(' ',max(case when RetSeq=1 then RetVal end)+' ')-1)
,Weight = IIF(A.Type=2,null,try_convert(decimal(5,1),replace(max(case when RetVal like '%PW' then RetVal end),'PW','')))
,Purity = try_convert(smallint ,replace(max(case when RetVal like '%K' then RetVal end),'K',''))
,Brand = IIF(A.Type=1,null,max(case when RetSeq=2 then RetVal end))
,Model = replace(max(case when RetVal Like 'Model[0-9,A-Z]%' then RetVal end),'Model','')
,SerialNum = replace(max(case when RetVal Like 'S/N[0-9,A-Z]%' then RetVal end),'S/N','')
From [dbo].[tvf-Str-Parse](CleanString,' ') B1
) C
Returns
The TVF if Interested
CREATE FUNCTION [dbo].[tvf-Str-Parse] (#String varchar(max),#Delimiter varchar(10))
Returns Table
As
Return (
Select RetSeq = Row_Number() over (Order By (Select null))
,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('<x>' + replace((Select replace(#String,#Delimiter,'§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
Cross Apply x.nodes('x') AS B(i)
);
EDIT - If you don't want or can't use a TVF
dbFiddle
Select A.Type
,A.Description
,C.*
From YourTable A
Cross Apply (values ( replace(
replace(
replace(
replace(A.Description,',',' ')
,' ',' ')
,'Model ','Model')
,'S/N ','S/N')
)
)B(CleanString)
Cross Apply (
Select Quantity = IsNull(left(max(case when RetSeq=1 then RetVal end),NullIf(patindex('%[^0-9]%',max(case when RetSeq=1 then RetVal end)) -1,0)),1)
,Name = substring(max(case when RetSeq=1 then RetVal end),patindex('%[^0-9]%',max(case when RetSeq=1 then RetVal end)),charindex(' ',max(case when RetSeq=1 then RetVal end)+' ')-1)
,Weight = IIF(A.Type=2,null,try_convert(decimal(5,1),replace(max(case when RetVal like '%PW' then RetVal end),'PW','')))
,Purity = try_convert(smallint ,replace(max(case when RetVal like '%K' then RetVal end),'K',''))
,Brand = IIF(A.Type=1,null,max(case when RetSeq=2 then RetVal end))
,Model = replace(max(case when RetVal Like 'Model[0-9,A-Z]%' then RetVal end),'Model','')
,SerialNum = replace(max(case when RetVal Like 'S/N[0-9,A-Z]%' then RetVal end),'S/N','')
From (
Select RetSeq = row_number() over (Order By (Select null))
,RetVal = ltrim(rtrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('<x>' + replace((Select replace(CleanString,' ','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
Cross Apply x.nodes('x') AS B(i)
) B1
) C
I'm following a YouTube series which teachs ASP.NET MVC. In the tutorial the teacher shows how to make a simple search functionality however in my case it's different.
I have search criteria: Studies (Dropdown), Country (Dropdown), Status (Dropdown) and Keyword (Input).
My question is how do I query the database to show the results depending on the search criteria that was chosen?
To be more clear:
If the User has chosen Studies and Country only then the code should use values from Studies and Country to search the respective database column.
Click here for the UI Design
Table: Students
[StudentID] INT IDENTITY (1, 1) NOT NULL,
[StudentName] VARCHAR (50) NOT NULL,
[StudentStudiesID] INT NOT NULL,
[StudentCountry] VARCHAR (50) NOT NULL,
[StudentCity] VARCHAR (50) NOT NULL,
[StudentStatus] VARCHAR (50) NOT NULL,
CONSTRAINT [PK_Students] PRIMARY KEY CLUSTERED ([StudentID] ASC),
CONSTRAINT [FK_Students_Studies] FOREIGN KEY ([StudentStudiesID]) REFERENCES [dbo].[Studies] ([StudiesID])
SearchController.cs
public class SearchController : Controller
{
public ActionResult Index()
{
DatabaseEntitiesModel db = new DatabaseEntitiesModel();
int Studies;
int.TryParse(Request.QueryString["Studies"], out Studies);
var Country = Request.QueryString["Country"];
var Status = Request.QueryString["Status"];
var Keyword = Request.QueryString["Keyword"];
IQueryable <Student> SearchQuery = db.Students;
List<SearchViewModel> SVM = SearchQuery.Select(x => new SearchViewModel
{
StudentID = x.StudentID,
StudentName = x.StudentName,
StudentCountry = x.StudentCountry,
StudentCity = x.StudentCity,
StudiesName = x.Study.StudiesName,
StudentStatus = x.StudentStatus
}).OrderByDescending(x => x.StudentID).ToList();
return View( SVM );
}
}
Reuse SearchQuery (items are lazy-loaded, until you call ToList()) and add as many specific Where() clauses/calls as you need:
// the type (IQueryable<Student>) should be defined explicitly
// details: https://stackoverflow.com/questions/21969154/cannot-implicitly-convert-type-system-linq-iqueryable-to-system-data-entity-d
IQueryable<Student> query = db.Students;
if(viewModel.Filter1 != null) {
query = query.Where(i => i.SomeStudentProperty1 == viewModel.Filter1);
}
if(viewModel.Filter2 != null) {
query = query.Where(i => i.SomeStudentProperty2 == viewModel.Filter2);
}
var result = query.ToList();
The easiest way to do this would be to test each condition and if it meets what you want, add a Where clause. Something like this:
int.TryParse(Request.QueryString["Studies"], out Studies);
var Country = Request.QueryString["Country"];
var Status = Request.QueryString["Status"];
var Keyword = Request.QueryString["Keyword"];
IQueryable<Student> SearchQuery = db.Students;
if(Studies > 0)
{
SearchQuery = SearchQuery.Where(s => s.StudiesID == Studies);
}
if(!string.IsNullOrEmpty(Country))
{
SearchQuery = SearchQuery.Where(s => s.StudentCountry == Country);
}
...More conditions can go here
Because of Lazy Loading, the actual query isn't executed until you call .ToList(), or iterate over the collection. Hopefully, this gets you started on the right track.
Edit
In my haste, I changed your IQueryable to a var. Fixed.
Also, as Erik pointed out, using Request.QueryString is not the way to go. You'll instead want to pass these values in to the action method. So, something like:
public ActionResult Index(int studies, string status, string country, string keyword)
I can't get this simple query right. I need to join my adresses table to my annonces table.
I supose this should be farly strait forward but I simply can't get it to work.
I firstly made my adresse table object like this
class AdressesTable extends Table
{
public function initialize(array $config)
{
$this->belongsTo('Annonces', [
'foreignKey' => 'annonceId',
'joinType' => 'INNER',
]);
}
}
Then in my annonces controller I tryed to join the adresses like this
public function view($id = null)
{
if (!$id) {
throw new NotFoundException(__('Annonce invalide!'));
}
$query = $this->Annonces->find('all', ['contain' => ['Adresses']])->where(['id' => $id]);
$annonce = $query->firstOrFail();
$this->set(compact('annonce'));
}
But then I got this error :
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Adresses.annonce_id' in 'where clause'
Witch I don't understand why I got it since I have defined my foreign key in the AdressesTable class.
The query I would like to have at the end would look like this
SELECT *
FROM annonces
INNER JOIN adresses ON adresses.annonceId = annonces.id
WHERE annonces.id = #param
*PS. I know it wont be select * but rather select [all my column]*
EDIT : My table schema are as following
CREATE TABLE annonces(
id INT NOT NULL AUTO_INCREMENT, #PK
startDate DATE NOT NULL,
endDate DATE NOT NULL,
title VARCHAR(128) NOT NULL,
descript TEXT NOT NULL,
infoSupplementaire TEXT NULL,
premium BIT NOT NULL,
clientId INT NOT NULL, #FK
categorieId INT NOT NULL, #FK
CONSTRAINT pk_annonces_id PRIMARY KEY (id),
CONSTRAINT fk_annonces_clientId FOREIGN KEY (clientId) REFERENCES clients(id),
CONSTRAINT fk_annonces_categorieId FOREIGN KEY (categorieId) REFERENCES categories(id)
);
CREATE TABLE adresses(
id INT NOT NULL AUTO_INCREMENT, #PK
latitude DECIMAL(11,7),
longitude DECIMAL(11,7),
adresse VARCHAR(512),
annonceId INT NOT NULL, #FK
CONSTRAINT pk_adresses_id PRIMARY KEY (id),
CONSTRAINT fk_adresses_annonceId FOREIGN KEY (annonceId) REFERENCES annonces(id)
)
I solved my problem by renaming my column folowing cakephp convention and using any of the code from this answer
You can try
$query = $this->Annonces->find('all', ['contain' => ['Adresses']])->where(['Annonces.id' => $id]);
$annonce = $query->firstOrFail();
OR
public function view($id = null)
{
if (!$id) {
throw new NotFoundException(__('Annonce invalide!'));
}
$annonceEntity = $this->Annonces->get($id);
$query = $this->Annonces->find('all', ['contain' => ['Adresses']])->where(['Annonces.id' => $annonceEntity->id]);
$annonce = $query->firstOrFail();
$this->set(compact('annonce'));
}
I use SPHINXSE And I query many index (like explained by Barryhunter here Joining on Multiple SphinxSE Tables In Single Query )
My problem is
In each index I have column with same name.
In my sphinxSe table I've fields named like these attributes.
When I run a query on only one index, theses fields are filled, but not when I use many index.
I'st a problem, because I would use id to simply identify from wich index is found the row.
As it's perhaps bette with source, find below my conf, and queries
in my sphinx.conf
source src_article_tv : article_base {
sql_query_pre = SET NAMES utf8
sql_query = \
SELECT /* sphinx index search article_tv_base */ \
concat (id,'40'), \
id AS ressource_id, \
'article' AS ressource_type, \ (...)
sql_attr_uint = ressource_id
sql_attr_string = ressource_type
(...)
source src_media_tv : media_base
{
sql_query_pre = SET NAMES utf8
sql_query = \
SELECT /* sphinx index search full media */ \
concat (o.id,'20'), \
o.id AS ressource_id, \
'media_tv' AS ressource_type, \
(...)
sql_attr_uint = ressource_id
sql_attr_string = ressource_type
delimiter $$
CREATE TABLE `tv_generic` (
`id` bigint(20) unsigned NOT NULL,
`weight` int(11) NOT NULL,
`query` varchar(3072) COLLATE utf8_unicode_ci NOT NULL,
`ressource_id` bigint(20) unsigned NOT NULL,
`ressource_type` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
KEY `query` (`query`(1024))
) ENGINE=SPHINX DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
CONNECTION='sphinx://127.0.0.1:9312/idx_tv'$$
So
with
SELECT * FROM search.tv_generic where query = 'mons;index=idx_article_tv';
or
SELECT * FROM search.tv_generic where query = 'mons;index=idx_media_tv';
fields ressource_id & ressource_type are filled (with the good values)
but with
SELECT * FROM search.tv_generic where query = 'mons;index=idx_article_tv,idx_media_tv';
fields ressource_id & ressource_type are '0'
I Found a "dirty" solution.
compat_sphinxql_magics = 1
and it's work.
It's still dirty because
compat_sphinxql_magics = 1 is deprecated http://sphinxsearch.com/forum/view.html?id=9239
I don't understand myself why it's work with compat_sphinxql_magics = 1
I woud like to inquire if my Linq solution below is a good solution or if there is a better way. I am new to using Linq, and am most familiar with MySQL. So I've been converting one of my past projects from PHP to .NET MVC and am trying to learn Linq. I would like to find out if there is a better solution than the one I came up with.
I have the following table structures:
CREATE TABLE maplocations (
ID int NOT NULL AUTO_INCREMENT,
name varchar(35) NOT NULL,
Lat double NOT NULL,
Lng double NOT NULL,
PRIMARY KEY (ID),
UNIQUE KEY name (name)
);
CREATE TABLE reservations (
ID INT NOT NULL AUTO_INCREMENT,
loc_ID INT NOT NULL,
resDate DATE NOT NULL,
user_ID INT NOT NULL,
PRIMARY KEY (ID),
UNIQUE KEY one_per (loc_ID, resDate),
FOREIGN KEY (user_ID) REFERENCES Users (ID),
FOREIGN KEY (loc_ID) REFERENCES MapLocations (ID)
);
CREATE TABLE Users (
ID INT NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
email VARCHAR(50) NOT NULL,
pass VARCHAR(128) NOT NULL,
salt VARCHAR(5) NOT NULL,
PRIMARY KEY (ID),
UNIQUE KEY unique_names (name),
UNIQUE KEY unique_email (email)
);
In MySQL, I use the following query to get the ealiest reservation at each maplocation with a non null date for any locations that don't have a reservation.
SELECT locs.*, if(res.resDate,res.resDate,'0001-01-01') as resDate, res.Name as User
FROM MapLocations locs
LEFT JOIN (
SELECT loc_ID, resDate, Name
FROM Reservations, Users
WHERE resDate >= Date(Now())
AND user_ID = Users.ID
ORDER BY resDate
) res on locs.ID = res.loc_ID
group by locs.ID
ORDER BY locs.Name;
In Linq, with Visual studio automatically creating much of the structure after connecting to the database, I have come up with the following equivalent to that SQL Query
var resList = (from res in Reservations
where res.ResDate >= DateTime.Today
select res);
var locAndRes =
(from loc in Maplocations
join res in resList on loc.ID equals res.Loc_ID into join1
from res2 in join1.DefaultIfEmpty()
join usr in Users on res2.User_ID equals usr.ID into join2
from usr2 in join2.DefaultIfEmpty()
orderby loc.ID,res2.ResDate
select new {
ID = (int)loc.ID,
Name = (string)loc.Name,
Lat = (double)loc.Lat,
Lng = (double)loc.Lng,
resDate = res2 != null ?(DateTime)res2.ResDate : DateTime.MinValue,
user = usr2 != null ? usr2.Name : null
}).GroupBy(a => a.ID).Select(b => b.FirstOrDefault());
So, I'm wondering is there a better way to perform this query?
Are these equivalent?
Are there any good practices I should be following?
Also, one more question, I'm having trouble getting this from the var to a List. doing something like this doesn't work
List<locAndResModel> locList = locAndRes.AsQueryable().ToList<locAndResModel>();
In the above snippet locAndResModel is just a class which has variables to match the int, string, double double, DateTime, string results of the query. Is there an easy way to get a list without having to do a foreach and passing the results to a constructor override? Or should I just add it to ViewData and return the View?
You'll want to take advantage of the automatic joins performed by the Entity Framework. Give this a try and let me know if it does what you want:
var locAndRes = from maplocation in MapLocations
let earliestReservationDate = maplocation.Reservations.Min(res => res.resDate)
let earliestReservation = (from reservation in mapLocation.Reservations
where reservation.resDate == earliestReservationDate && reservation.resDate >= DateTime.Today
select reservation).FirstOrDefault()
select new locAndResModel( maplocation.ID, maplocation.name, maplocation.Lat, maplocation.Lng, earliestReservation != null ? earliestReservation.resDate : DateTime.MinValue, earliestReservation != null ?earliestReservation.User.name : null)